package com.gjintel.business.proj.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import com.gjintel.auction.business.model.AuctionInfo;
import com.gjintel.sdk.util.*;
import net.sf.json.JsonConfig;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.business.proj.model.BidderChange;
import com.gjintel.business.proj.model.ComposeIdPK;
import com.gjintel.business.proj.model.ComposeIdPK2;
import com.gjintel.business.proj.model.DepositReturn;
import com.gjintel.business.proj.model.DepositReturnOut;
import com.gjintel.business.proj.model.ProfessorInfo;
import com.gjintel.business.proj.model.ProjectBidInfo;
import com.gjintel.business.proj.model.ProjectInfo;
import com.gjintel.business.proj.model.ProjectPause;
import com.gjintel.business.proj.service.IDepositReturnService;
import com.gjintel.business.proj.service.IProfessorService;
import com.gjintel.business.proj.service.IProjectBidService;
import com.gjintel.business.proj.service.IProjectInfoService;
import com.gjintel.business.proj.service.IProjectPauseService;
import com.gjintel.business.proj.service.impl.NotifyServiceImpl;
import com.gjintel.business.webcontent.dto.Combo;
import com.gjintel.business.webcontent.model.WebContent;
import com.gjintel.business.webcontent.service.IWebContentService;
import com.gjintel.framework.common.service.IDepositExecuteService;
import com.gjintel.framework.common.service.IDepositService;
import com.gjintel.framework.constant.ActivitiMap;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.constant.ProjectStatus;
import com.gjintel.framework.dataset.model.DataSet;
import com.gjintel.framework.dict.model.Dictionary;
import com.gjintel.framework.holidayset.service.IHolidaySetService;
import com.gjintel.framework.log.model.LogInfo;
import com.gjintel.framework.log.util.LogUtil;
import com.gjintel.framework.log.util.LogUtil.LogType;
import com.gjintel.framework.projecttype.model.ProjectType;
import com.gjintel.framework.projecttype.service.IProjectTypeService;
import com.gjintel.framework.register.model.RegisterUser;
import com.gjintel.framework.register.service.IRegisterUserService;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.role.model.Role;
import com.gjintel.framework.role.service.IRoleService;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.user.model.UserRole;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.DictUtil;
import com.gjintel.framework.util.FileResUtil;
import com.gjintel.framework.util.dto.Bank;
import com.gjintel.framework.validateunique.service.IValidateUniqueService;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.workflow.trade.service.IWorkflowProcessInstanceService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @description
 * @author wwang
 * @date 2016-8-31
 */
@RequestMapping("/business/projectmanage")
@Controller
@SuppressWarnings("unchecked")
public class ProjectBidController {

	@SuppressWarnings("unused")
	private static final Logger LOG = Logger.getLogger(ProjectBidController.class);

	/*** 禁投 */
	private static Integer ISNOBID = 1;

	/*** 没有禁投 */
	private static Integer NOISNOBID = 0;

	@Autowired
	private IProjectInfoService projectInfoService;

	@Autowired
	private IWorkflowProcessInstanceService workflowProcessInstanceService;

	@Autowired
	private IProjectTypeService projectTypeService;

	@Autowired
	private IRoleService roleService;

	@Autowired
	private IProjectBidService projectBidService;

	@Autowired
	private IRegisterUserService registerUserService;

	@Autowired
	private IDepositService depositService;

	@Autowired
	private IProfessorService professorService;

	@Autowired
	private IProjectPauseService profectPauseService;

	@Autowired
	private IDepositReturnService depositReturnService;

	@Autowired
	private IHolidaySetService holidaySetServiceImpl;

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private  IDepositExecuteService executeDepositService;

	@Autowired
	private IDepositExecuteService depositExecuteService;

	@Autowired
	private NotifyServiceImpl notifyService;

	/** 竞价公示暂停 */
	private String BID_PAUSE = "101";
	/** 中标公示暂停 */
	private String HIT_PAUSE = "102";
	/** 质疑投诉 */
	private String OPPUGN_PAUSE = "103";
	/** 变更公告 */
	private String EDITPUBLISH = "104";

	@Autowired
	private IWebContentService webContentService;

	@Autowired
	private IValidateUniqueService validateUniqueService;

	/**
	 * 专家项目评标列表
	 *
	 * @param session
	 * @return
	 */
	@RequestMapping("/expert/expert")
	public ModelAndView audit(HttpSession session) {
		ModelAndView mv = new ModelAndView("/proj/expert/project-expert");
		User user = (User) session.getAttribute("loginUser");
		// 获取项目类型
		List<ProjectType> projectTypeList = projectTypeService.findAll();
		mv.addObject("projectTypeList", projectTypeList);
		return mv;
	}

	/**
	 * @description 专家项目评标列表List
	 * @author wwang
	 * @date 2016-8-23
	 * @param session
	 * @param project
	 * @param page
	 * @param sort
	 * @param startTime
	 * @param stopTime
	 * @param bidTime
	 * @param bidStopTime
	 * @param roleId
	 * @return
	 */
	@RequestMapping("/expert/expertList")
	@ResponseBody
	public JSONObject expertList(HttpSession session, ProjectInfo project, Page page, Sort sort,
			java.sql.Date startTime, java.sql.Date stopTime, java.sql.Date bidTime, java.sql.Date bidStopTime,
			String roleId) {
		User user = (User) session.getAttribute("loginUser");
		RegisterUser registerUser = this.projectInfoService.get(RegisterUser.class, user.getRegisterId());
		// 结束时间处理，加一天
		stopTime = StringUtil.addOneDayDate(stopTime, 1);
		bidStopTime = StringUtil.addOneDayDate(bidStopTime, 1);

		projectInfoService.findProjectBiddList(project, page, sort, startTime, stopTime, bidTime, bidStopTime);

		// 数据处理

		// 获取用户额所以角色ids
		String roleIds = "";
		List<Role> roleList = roleService.findRolesByUserId(user.getId());
		for (Role role : roleList) {
			roleIds += "'" + role.getId() + "',";
		}
		if (roleIds.length() > 0) {
			roleIds = roleIds.substring(0, roleIds.length() - 1);
		}

		List<ProjectInfo> pageList = page.getResult();
		for (ProjectInfo pro : pageList) {
			pro.setStatusName(DictUtil.dict("proj_status", pro.getStatus() + "").getName());// 项目状态

			// 操作菜单
//			String opera = "";
//			List<ProjectOperation> list = roleService.findOperationByRoleIdAndStatus(roleIds, pro.getStatus() + "");
//			for (ProjectOperation op : list) {
//				if (op.getRoleId().equals(ActivitiMap.getProperty(roleId))) {
//					opera += op.getActionUrl().replace("row.id", pro.getId());
//				}
//			}
//
//			// 添加项目详情操作
//			opera += Constant.DETAILS_OPERATION.replace("row.id", pro.getId());
//			pro.setOperation(opera);
		}
		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * @description 跳转投标信息页面
	 * @author wwang
	 * @date 2016-8-31
	 * @param projectId
	 */
	@RequestMapping("/expert/evaluateInput")
	@ResponseBody
	public ModelAndView evaluateInput(String projectId, HttpSession session) {
		ModelAndView mv = new ModelAndView("/proj/expert/evaluate-input");
		ProjectInfo project = this.projectBidService.get(ProjectInfo.class, projectId);
		mv.addObject("project", project);
		mv.addObject("projectId", projectId);
		return mv;
	}

	/**
	 * @description 项目负责人跳转投标信息页面
	 * @author wwang
	 * @date 2016-8-31
	 * @param projectId
	 */
	@RequestMapping("/leader/evaluateInput")
	@ResponseBody
	public ModelAndView leaderEvaluateInput(String projectId, HttpSession session) {
		ModelAndView mv = new ModelAndView("/proj/leader/evaluate-input");
		ProjectInfo project = this.projectBidService.get(ProjectInfo.class, projectId);
		mv.addObject("project", project);
		mv.addObject("projectId", projectId);
		return mv;
	}

	/**
	 * @description 专家评标列表List
	 * @author wwang
	 * @date 2016-8-31
	 * @param session
	 * @return
	 */
	@RequestMapping("/expert/expertBidList")
	@ResponseBody
	public JSONObject expertBidList(HttpSession session, Page page, ProjectBidInfo bidInfo) {
		User user = (User) session.getAttribute("loginUser");
		RegisterUser registerUser = this.projectInfoService.get(RegisterUser.class, user.getRegisterId());
		if (registerUser != null) {// 是否为投标人，当开标时，投标人可查看自己的投标信息
//			ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, bidInfo.getProjectId());
//			// 开标后 投标人可看见所有的投标信息
//			List<Integer> projectStatusList = getProjectStatusList();
//			if (projectStatusList.contains(project.getStatus())) {// 中标公示后所有投标人都可见
//				bidInfo.setUserId(null);
//			} else {
//				bidInfo.setUserId(registerUser.getId());
//			}
			bidInfo.setUserId(registerUser.getId());
		}
		this.projectInfoService.findProjectBidListByProjectId(page, bidInfo);
		List<ProjectBidInfo> list = page.getResult();
		for (ProjectBidInfo info : list) {
			RegisterUser bidder = this.projectInfoService.get(RegisterUser.class, info.getUserId());
			info.setSocietyCode(bidder.getSocietyCode());
			if (bidder.getForbidStartDate() != null) {
				Date forbidStartDate = bidder.getForbidStartDate();// 禁投开始日期
				Date forbidEndDate = bidder.getForbidEndDate();// 禁投结束日期
				if (forbidStartDate != null && forbidEndDate != null && forbidEndDate.compareTo(new Date()) >= 0) {// 禁投结束日期大于当前日期
					info.setIsNoBid(ISNOBID);// 是禁投

					// 查询此投标人的曝光情况
					List<WebContent> webList = this.webContentService.findWebByBusinessId(bidder.getId());
					if (webList != null && webList.size() > 0) {
						info.setNewWebContentId(webList.get(0).getId());// 获取最新一条
					}
				} else {
					info.setIsNoBid(NOISNOBID);// 不是禁投
				}
			}
		}

		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * @description 获取投标人能查看项目投标信息项目状态集合
	 * @author wwang
	 * @date 2016年9月18日
	 */
	private List<Integer> getProjectStatusList() {
		// List<Integer> list = new ArrayList<Integer>();
		// list.add(10);
		// list.add(11);
		// list.add(110);
		// list.add(12);
		// list.add(27);
		// list.add(28);
		// list.add(13);
		// list.add(14);
		// list.add(140);
		// list.add(142);
		// list.add(143);
		// list.add(141);
		// list.add(15);
		// list.add(16);
		// list.add(24);
		// list.add(29);
		// list.add(30);
		// list.add(88);
		// return list;
		List<Integer> list = new ArrayList<Integer>();
		list.addAll(Arrays.asList(Integer.valueOf(ProjectStatus.SHOWING.toString()),
				Integer.valueOf(ProjectStatus.SHOW_OVER.toString()),
				Integer.valueOf(ProjectStatus.SHOWING_FLOW.toString()), Integer.valueOf(ProjectStatus.ALERT.toString()),
				Integer.valueOf(ProjectStatus.WAIT_CONTACT_AUDIT.toString()),
				Integer.valueOf(ProjectStatus.CONTACT_AUDIT_NOT_PASS.toString()),
				Integer.valueOf(ProjectStatus.SHOW_CONTACT.toString()),
				Integer.valueOf(ProjectStatus.SHOW_CONTACT_OVER.toString()),
				Integer.valueOf(ProjectStatus.WAIT_RECEIVING.toString()),
				Integer.valueOf(ProjectStatus.RECEIVING_UNAUTH.toString()),
				Integer.valueOf(ProjectStatus.RECEIVING_SHOWING.toString()),
				Integer.valueOf(ProjectStatus.WAIT_PROJ_OVER_SURE.toString()),
				Integer.valueOf(ProjectStatus.PROJ_OVER.toString()),
				Integer.valueOf(ProjectStatus.FLOW_DOWN.toString()), Integer.valueOf(ProjectStatus.CANCEL.toString()),
				Integer.valueOf(ProjectStatus.COMPAT_SHOW_PAUSE.toString()),
				Integer.valueOf(ProjectStatus.HIT_SHOW_PAUSE.toString()),
				Integer.valueOf(ProjectStatus.STATUS_LOCK.toString())));
		return list;
	}

	/**
	 * @description 专家评标通过操作
	 * @author wwang
	 * @date 2016-8-31
	 * @param bidInfo
	 * @return
	 */
	@RequestMapping("/expert/doSubmitEvaluatePass")
	@ResponseBody
	public String doSubmitEvaluatePass(ProjectBidInfo bidInfo) {
		ProjectBidInfo pb = this.projectInfoService.get(ProjectBidInfo.class, bidInfo.getId());
		if (pb.getEvalutionResult() != null) {
			if (pb.getEvalutionResult() == 2) {// 已被项目负责人设为无效标了
				return Constant.UNSUCCESS;
			}
		}
		pb.setEvalutionResult(1);// 通过
		pb.setEvalutionTime(new Date());
		this.projectInfoService.saveOrUpdate(pb);
		return Constant.SUCCESS;
	}

	/**
	 * @description 项目负责人评标无效标操作
	 * @author wwang
	 * @date 2016-8-31
	 * @param bidInfo
	 * @return
	 */
	@RequestMapping("/expert/doSubmitInvalidBid")
	@ResponseBody
	public String doSubmitInvalidBid(ProjectBidInfo bidInfo) {
		ProjectBidInfo pb = this.projectInfoService.get(ProjectBidInfo.class, bidInfo.getId());
		pb.setEvalutionResult(2);// 无效标
		pb.setEvalutionTime(new Date());
		this.projectInfoService.saveOrUpdate(pb);
		return Constant.SUCCESS;
	}

	/**
	 * @description 查看投标信息详情
	 * @author xuyefei
	 * @date 2016-4-13 下午07:50:45
	 * @return ModelAndView
	 */
	@RequestMapping("/getBidDetail")
	public ModelAndView getBidDetail(HttpSession session, String id) {
		ModelAndView mv = new ModelAndView("/proj/expert/projectbid-detail");
		ProjectBidInfo pb = this.projectInfoService.get(ProjectBidInfo.class, id);
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, pb.getProjectId());
		mv.addObject("pb", pb);
		mv.addObject("project", project);

		// 投标上传的文件
		if (!StringUtil.isEmpty(pb.getProjectId())) {
			List<Resources> resList = FileResUtil.findResources(project.getId() + "," + pb.getUserId());
			mv.addObject("resList", resList);
		}
		return mv;
	}

	/**
	 * @description 项目负责人评标初审结束
	 * @author wwang
	 * @date 2016-8-31
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/leader/firstEvaluateBidEnd")
	@ResponseBody
	public String firstEvaluateBidEnd(String projectId) {
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);

		// 检验专家和项目负责人的评标操作
		// 有效标不足三家，未评标和有效标大于三家
		int effectiveCount = this.projectBidService.getProjectBidCountByProjIdAndEvalutionResult(projectId,
				Constant.EFFECTIVE);// 有效标
		int noEvaluationCount = this.projectBidService.getProjectBidCountByProjIdAndEvalutionResult(projectId,
				Constant.NOEVALUATIONCOUNT);// 未评标
		if (effectiveCount < 3 && (noEvaluationCount + effectiveCount) >= 3) {
			return "evaluationcountnocomplete";// 评标未完成
		}

		// 处理剩余未评标的投标信息,统一状态改为“不需评标”
		List<ProjectBidInfo> bidList = projectBidService.getProjectBidCount(projectId);
		for (ProjectBidInfo pb : bidList) {
			if (pb.getEvalutionResult() == 0) {// 未评标
				ProjectBidInfo bidInfo = this.projectBidService.get(ProjectBidInfo.class, pb.getId());
				bidInfo.setEvalutionResult(3);// 不需评标
				this.projectBidService.saveOrUpdate(bidInfo);
			}
		}

		// 设置项目状态为初审结束
		project.setStatus(Integer.valueOf(ProjectStatus.AUDITED_END.toString()));
		this.projectInfoService.saveOrUpdate(project);
		// 流程 完成任务
		Task task = workflowProcessInstanceService.findTask(project.getWorkflowId());
		workflowProcessInstanceService.complete(task.getId(), null);
		return Constant.SUCCESS;
	}

	/**
	 * @description 打印询标函
	 * @author wwang
	 * @date 2016-9-1
	 * @param session
	 * @param projectId
	 * @param bidderId
	 * @return
	 */
	@RequestMapping("/public/letterPrint")
	public ModelAndView letterPrint(HttpSession session, String projectId, String bidderId) {
		ModelAndView mv = new ModelAndView("/proj/public/letter-print");
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		RegisterUser register = this.projectInfoService.get(RegisterUser.class, bidderId);// 投标人信息

		mv.addObject("project", project);
		mv.addObject("register", register);
		return mv;
	}

	/**
	 * @description 评标结束 页面
	 * @author wwang
	 * @date 2016年9月5日
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/leader/evaluationBidEndInput")
	@ResponseBody
	public ModelAndView evaluationBidEndInput(String projectId) {
		ModelAndView mv = new ModelAndView("/proj/leader/evaluationBidEnd-input");
		// 项目信息
		ProjectInfo project = projectInfoService.get(ProjectInfo.class, projectId);
		boolean isFlow = projectInfoService.getProjectBidderByProjId(projectId, true) < 3;// 是否流标

		DataSet dataset = projectInfoService.get(DataSet.class, Constant.DATASET_ID);
		mv.addObject("project", project);
		mv.addObject("dataset", dataset);
		mv.addObject("isFlow", isFlow);
		return mv;
	}

	/**
	 * @description 评标结束
	 * @author wwang
	 * @date 2016年9月5日
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/leader/evaluationBidEnd")
	@ResponseBody
	public String evaluationBidEnd(ProjectInfo project, Integer showEndDay, String budgetMenuData) throws Exception {
		// 项目信息
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, project.getId());
		pro.setEvaluteEndTime(new Date());// 评标结束时间
		pro.setHitShowPeriod(project.getHitShowPeriod());
		// String publicityDate = StringUtil.computeDate(new Date(), "00:00:00",
		// showEndDay+1);//公示时间
		// pro.setShowEndTime(new SimpleDateFormat("yyyy-MM-dd
		// HH:mm:ss").parse(publicityDate));//中标公示结束时间

		//计算中标/流标超时未确认时间(三个工作日)
		String bidConfirmDateStr = DateUtils.computeWorkDayDateStr(holidaySetServiceImpl, new Date(), 3);
		String bidConfirmDate=StringUtil.getISODate(bidConfirmDateStr);

		// 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(pro.getId());
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}

		// 完成任务
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		Map<String, Object> variables = new HashMap<String, Object>();
		// 校验有效标是否大于三家，否则流标确认
		if (projectInfoService.getProjectBidderByProjId(project.getId(), true) < 3) {// 流标待确认
			variables.put("tenderPass", false);
			pro.setStatus(Integer.valueOf(ProjectStatus.WAIT_FAIL_SURE.toString()));
		} else {// 中标待确认
				// projectInfoService.saveTendeeByProjId(pro.getId());//最低价中标
			variables.put("tenderPass", true);
			pro.setStatus(Integer.valueOf(ProjectStatus.WAIT_WIN_SURE.toString()));
		}
		variables.put("bidConfirmDate", bidConfirmDate);//设置中标/流标超时未确认时间(三个工作日)

		workflowProcessInstanceService.complete(task.getId(), variables);
		this.projectInfoService.saveOrUpdate(pro);
		return Constant.SUCCESS;
	}

	/**
	 * @description 采购人中标/流标确认
	 * @author wwang
	 * @date 2016年9月5日
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/buyer/bidEndSure")
	@ResponseBody
	public String bidEndSure(ProjectInfo project, String budgetMenuData) throws Exception {
		// 项目信息
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, project.getId());

		// 完成任务
		Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
		Map<String, Object> variables = new HashMap<String, Object>();
		// 获取中标公示结束时间
		// String publicityDate = StringUtil.computeDate(new Date(), "00:00:00",
		// pro.getHitShowPeriod()+1);//公示时间
		// 校验有效标是否大于三家，否则自动流标
		if (projectInfoService.getProjectBidderByProjId(project.getId(), true) < 3) {// 流标待确认
			variables.put("tenderPass", false);
			pro.setStatus(Integer.valueOf(ProjectStatus.FLOW_DOWN.toString()));
		} else {// 中标待确认

			// 推送信息至银行（履约保证金）
//			boolean executeResult = postBankFromExecute(pro);
//			if (!executeResult) {//履约保证金推送失败
//				return "postbanexecutekfaill";
//			}


			String publicityDate = DateUtils.computeWorkDayDateStr(holidaySetServiceImpl, new Date(),
					pro.getHitShowPeriod());// (工作日)公示时间
			pro.setShowEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(publicityDate));// 中标公示结束时间
			variables.put("timeHit", StringUtil.getISODate(pro.getShowEndTime()));
			variables.put("tenderPass", true);
			pro.setStatus(Integer.valueOf(ProjectStatus.SHOWING.toString()));
		}
		//交易时间
		pro.setTradeTime(new Date());
		workflowProcessInstanceService.complete(task.getId(), variables);
		this.projectInfoService.saveOrUpdate(pro);
		return Constant.SUCCESS;
	}


	/**
	 * 推送信息至银行操作（履约保证金）
	 * @return
	 */
	public boolean postBankFromExecute(AuctionInfo pi) {

		// 第一次
		int n = 1;

		try {
			int _ret = depositExecuteService.regToBank(pi.getId());
			if (_ret == 1) {
				System.out.print("注册成功!");
				return true;
			} else {
				System.out.print("注册 不成功");
				n++;
			}
		} catch (IOException e) {
			System.out.print("注册 不成功，出现异常");
			e.printStackTrace();
			n++;
		}

		// 第二次
		try {
			int _ret = depositExecuteService.regToBank(pi.getId());
			if (_ret == 1) {
				System.out.print("第二次注册成功!");
				return true;
			} else {
				System.out.print("第二次注册 不成功");
				n++;
			}
		} catch (IOException e) {
			System.out.print("第二次注册 不成功，出现异常");
			e.printStackTrace();
			n++;
		}

		// 第三次
		try {
			int _ret = depositExecuteService.regToBank(pi.getId());
			if (_ret == 1) {
				System.out.print("第三次注册成功!");
				return true;
			} else {
				System.out.print("第三次注册 不成功");
				n++;
			}
		} catch (IOException e) {
			System.out.print("第三次注册 不成功，出现异常");
			e.printStackTrace();
			n++;
		}

		if (n >= 3) {
			// 发布三次未注册上的消息给系统管理 员
			this.notifyService.savePostBankFallNotify(pi);
			return false;
		}
		return false;
	}

	// /**
	// * @description 采购人结项确认
	// * @author wwang
	// * @date 2016年9月5日
	// * @param projectId
	// * @return
	// */
	// @RequestMapping("/buyer/projectEndSure")
	// @ResponseBody
	// public String projectEndSure(ProjectInfo project,String budgetMenuData){
	// // 项目信息
	// ProjectInfo pro = projectInfoService.get(ProjectInfo.class,
	// project.getId());
	// pro.setEndTime(new Date());
	// //TODO wei 项目跨度
	// int allDays=DateUtils.daysBetween(pro.getEndTime(),pro.getCreateTime());
	// pro.setAllDays(allDays);
	// pro.setStatus(Integer.valueOf(ProjectStatus.PROJ_OVER.toString()));
	// // 完成任务
	// Task task = workflowProcessInstanceService.findTask(pro.getWorkflowId());
	//
	// workflowProcessInstanceService.complete(task.getId(), null);
	// this.projectInfoService.saveOrUpdate(pro);
	// return Constant.SUCCESS;
	// }

	/**
	 * @description 评审纪要
	 * @author shy
	 * @date 2016-9-6
	 */

	@RequestMapping("/print/reviewRecord")
	public ModelAndView printReviewRecord(HttpSession session, String projectId) {
		ModelAndView mv = new ModelAndView("/proj/reviewFile/ReviewRecordNew");
		ProjectInfo pi = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		Date bidStartTime = pi.getBidStartTime();

		String winningId = pi.getWinningId();
		if (!StringUtil.isEmpty(winningId)) {
			List<ProjectBidInfo> list = this.projectBidService.getProjectBid(projectId, winningId);
			if (list.size() > 0) {
				ProjectBidInfo pb = list.get(0);
				mv.addObject("projectBid", pb);
			}
		} else {
			pi.setWinningName("");
		}
		List<ProjectBidInfo> list = this.projectBidService.getProjectBidCount(projectId);
		// 有效标数量
		int effectiveCount = this.projectBidService.getProjectBidCountByProjIdAndEvalutionResult(projectId,
				Constant.EFFECTIVE);
		mv.addObject("project", pi);
		mv.addObject("bidcount", list.size());
		mv.addObject("time", bidStartTime);
		mv.addObject("effectiveCount", effectiveCount);
		return mv;
	}

	/**
	 * @description 打印签到表
	 * @author shy
	 * @date 2016-9-7
	 */
	@RequestMapping("/print/signIn")
	public ModelAndView signInTable(HttpSession session, String projectId) {
		List<ProfessorInfo> professors = new ArrayList<ProfessorInfo>();
		ModelAndView mv = new ModelAndView("/proj/reviewFile/signIn");
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		List<ProfessorInfo> professorList = professorService.getProfessorList(projectId);
		int size = professorList.size();
		int j = 0;
		for (int i = 0; i < 10; i++) {
			if (j < size) {
				ProfessorInfo professorInfo = professorList.get(j);
				professors.add(professorInfo);
			}
			if (j >= size) {
				ProfessorInfo professorInfo = new ProfessorInfo();
				professors.add(professorInfo);
			}
			j++;
		}
		mv.addObject("professorList", JSONArray.fromObject(professors));
		mv.addObject("project", project);
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");
		mv.addObject("date", sdf1.format(new Date()));
		return mv;
	}

	/**
	 * @description 专家监督人员劳务费支出表范本
	 * @author shy
	 * @date 2016-9-7
	 */

	@RequestMapping("/print/serviceCharge")
	public ModelAndView serviceCharge(HttpSession session, String projectId) {
		ModelAndView mv = new ModelAndView("/proj/reviewFile/serviceCharge");
		ProjectInfo pi = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		mv.addObject("project", pi);
		return mv;
	}

	/**
	 * @description 合肥市包河区政府采购中心投标文件签收登记表
	 * @author shy
	 * @date 2016-9-7
	 */
	@RequestMapping("/print/projectBid")
	public ModelAndView projectBid(HttpSession session, String projectId) {
		ProjectInfo pi = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		List<ProjectBidInfo> list = this.projectBidService.getProjectBid(projectId);
		// System.out.println(list.toArray());
		ModelAndView mv = new ModelAndView("/proj/reviewFile/projectBid");
		mv.addObject("projectBidList", list);
		mv.addObject("projectInfo", pi);
		return mv;
	}

	/**
	 * @description 报价表
	 * @author shy
	 * @date 2016-11-1
	 */
	@RequestMapping("/print/quote")
	public ModelAndView quote(HttpSession session, String projectId) {
		ProjectInfo pi = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		List<ProjectBidInfo> list = this.projectBidService.getProjectBidCount(projectId);
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");
		ModelAndView mv = new ModelAndView("/proj/reviewFile/quote");
		mv.addObject("date", sdf1.format(new Date()));
		mv.addObject("projectBidList", list);
		mv.addObject("projectInfo", pi);
		return mv;
	}

	/**
	 * 项目时间列表页面
	 *
	 * @param session
	 * @return
	 */
	@RequestMapping("/public/projSchedule")
	public ModelAndView projSchedule(HttpSession session) {
		ModelAndView mv = new ModelAndView("/proj/public/project-schedule");
		User user = (User) session.getAttribute("loginUser");
		// 获取项目类型
		List<ProjectType> projectTypeList = projectTypeService.findAll();
		mv.addObject("projectTypeList", projectTypeList);
		return mv;
	}

	/**
	 * 项目时间列表list
	 *
	 * @param session
	 * @param project
	 * @param page
	 * @param sort
	 * @param startTime
	 * @param stopTime
	 * @param bidTime
	 * @param bidStopTime
	 * @param roleId
	 * @return
	 */
	@RequestMapping("/public/projScheduleList")
	@ResponseBody
	public JSONObject projScheduleList(HttpSession session, ProjectInfo project, Page page, Sort sort,
			java.sql.Date startTime, java.sql.Date stopTime, java.sql.Date bidTime, java.sql.Date bidStopTime,
			String roleId) {
		User user = (User) session.getAttribute("loginUser");
		// 结束时间处理，加一天
		stopTime = StringUtil.addOneDayDate(stopTime, 1);
		bidStopTime = StringUtil.addOneDayDate(bidStopTime, 1);

		// 获取项目列表
		project.setAuditable(null);
		this.projectInfoService.findAllByIds(null, project, page, sort, startTime, stopTime, bidTime, bidStopTime, null,
				null);

		List<ProjectInfo> pageList = page.getResult();
		for (ProjectInfo pro : pageList) {
			// 处理项目状态
			Dictionary dicProStatus = DictUtil.dict("proj_status", pro.getStatus() + "");
			if (dicProStatus != null) {
				pro.setStatusName(dicProStatus.getName());// 项目状态
			} else {
				pro.setStatusName("未知");// 项目状态
			}
		}
		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * @description
	 * @author wwang 打开归档资料选择页面
	 * @date 2016-8-31
	 * @param projectId
	 */
	@RequestMapping("/leader/pigeonholeInput")
	@ResponseBody
	public ModelAndView pigeonholeInput(String projectId, HttpSession session) {
		User user = (User) session.getAttribute("loginUser");
		UserRole userRole = roleService.findUserRole(ActivitiMap.BUYER_ID, user.getId());// 是否为采购人
		UserRole manageRole = roleService.findUserRole(ActivitiMap.MANAGER_ID, user.getId());// 是否为项目负责人
		UserRole bizmanageRole = roleService.findUserRole(ActivitiMap.BIZMANAGER_ID, user.getId());// 是否为业务管理员

		ModelAndView mv = new ModelAndView("/proj/leader/file-pigeonhole-list");
		List<Resources> resList = FileResUtil.findResources(projectId);
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		List<Dictionary> projectFileList = DictUtil.dictChildren("projectFileName");
//		if(Constant.PROJECTCATAGORY_ENGINEERINGID.equals(project.getCatagoryId())){//工程类
//			for (Dictionary dic : projectFileList) {
//				if("2".equals(dic.getValue())){//项目需求--->清单图纸等资料
//					dic.setName("清单图纸等资料");
//				}
//				if("8".equals(dic.getValue())){//采购需求--->工程需求
//					dic.setName(dic.getName()+"：工程需求");
//				}
//			}
//		}else if(Constant.PROJECTCATAGORY_SERVICEID.equals(project.getCatagoryId())){//服务类
//			for (Dictionary dic : projectFileList) {
//				if("2".equals(dic.getValue())){//项目需求
//					dic.setName("项目需求");
//				}
//				if("8".equals(dic.getValue())){//采购需求--->服务需求
//					dic.setName(dic.getName()+"：服务需求");
//				}
//			}
//		}else{//货物类(其他)
//			for (Dictionary dic : projectFileList) {
//				if("2".equals(dic.getValue())){//项目需求
//					dic.setName("项目需求");
//				}
//				if("8".equals(dic.getValue())){//采购需求--->服务需求
//					dic.setName(dic.getName()+"：采购需求");
//				}
//			}
//		}

		// 投标人文件选择
		ProjectBidInfo projectBidInfo = new ProjectBidInfo();
		projectBidInfo.setProjectId(projectId);
		List<ProjectBidInfo> bidInfoList = this.projectInfoService.findProjectBidListByProjectId(null, projectBidInfo);

		//竞价公示暂停附件
		List<Resources> shotPauseResList=new ArrayList<>();
		List<ProjectPause> shotPauseList = this.profectPauseService.getPrjectPause(project.getId(), "0");
		for (ProjectPause pause : shotPauseList) {
			List<Resources> resourcesList = FileResUtil.findResources(pause.getId());
			shotPauseResList.addAll(resourcesList);
		}

		//中标公示暂停附件
		List<Resources> bidPauseResList=new ArrayList<>();
		List<ProjectPause> bidPauseList = this.profectPauseService.getPrjectPause(project.getId(), "1");
		for (ProjectPause pause : bidPauseList) {
			List<Resources> resourcesList = FileResUtil.findResources(pause.getId());
			bidPauseResList.addAll(resourcesList);
		}

		mv.addObject("bidInfoList", bidInfoList);
		mv.addObject("projectId", projectId);
		mv.addObject("project", project);
		mv.addObject("resList", resList);
		mv.addObject("shotPauseResList", shotPauseResList);
		mv.addObject("bidPauseResList", bidPauseResList);
		mv.addObject("projectFileList", projectFileList);
		if (userRole != null&&manageRole==null&&bizmanageRole==null) {// 不为空，是采购人,且不是项目怒负责人和业务管理员
			mv.addObject("isBuyer", true);
		}
		return mv;
	}

	/**
	 * @description归档 文件导出下载
	 * @author wwang
	 * @date 2016年9月9日
	 * @param resId
	 * @param response
	 * @param request
	 * @throws Exception
	 * @throws Exception
	 */
	@RequestMapping("/leader/exportAllFile")
	public void exportAllFile(String resId, HttpServletResponse response, HttpServletRequest request, String projectId,
			String[] resIds, String[] bidderIds) throws Exception {
		List<File> tenpFileList = new ArrayList<File>();// 临时问价集合
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);
		List<String> resIdsList = new ArrayList<String>();
		if (resIds != null) {
			resIdsList = Arrays.asList(resIds);
		}
		List<Resources> resList = FileResUtil.findResources(projectId);
		// 1获取项目相关的资料
		List<File> fileList = new ArrayList<File>();
		List<String> fileNameList = new ArrayList<String>();
		for (Resources res : resList) {
			if (resIdsList.contains(res.getFunctionFlog().toString())) {// 选择了
				// 获取此资源文件的数据字典信息
				int fileIndex = DictUtil.dict("projectFileName", res.getFunctionFlog() + "").getDisSort();// 排序值
				// 打包
				// 获取文件服务器真实路径
				String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
				String filePath = request.getSession().getServletContext().getRealPath("/");
				fileRealPath = filePath + "file_resource" + fileRealPath;
				// 文件上传的真实名
				fileNameList.add(fileIndex + "-" + res.getOldName());
				File file = new File(fileRealPath);
				fileList.add(file);
			}
		}

		// 1.2、获取竞价公示暂停资料
		if (resIdsList.contains(BID_PAUSE)) {
			List<ProjectPause> shotPauseList = this.profectPauseService.getPrjectPause(project.getId(), "0");
			for (ProjectPause pause : shotPauseList) {
				List<Resources> resourcesList = FileResUtil.findResources(pause.getId());
				for (Resources res : resourcesList) {
					// 打包
					// 获取此资源文件的数据字典信息
					int fileIndex = DictUtil.dict("projectFileName", res.getFunctionFlog() + "").getDisSort();// 排序值
					// 获取文件服务器真实路径
					String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
					String filePath = request.getSession().getServletContext().getRealPath("/");
					fileRealPath = filePath + "file_resource" + fileRealPath;
					// 文件上传的真实名
					fileNameList.add(fileIndex + "-" + res.getOldName());
					File file = new File(fileRealPath);
					fileList.add(file);
				}
			}
		}

		// 1.3、获取竞价中标暂停资料
		if (resIdsList.contains(HIT_PAUSE)) {
			// 1、中标公示暂停信息
			List<ProjectPause> bidPauseList = this.profectPauseService.getPrjectPause(project.getId(), "1");
			for (ProjectPause pause : bidPauseList) {
				List<Resources> resourcesList = FileResUtil.findResources(pause.getId());
				for (Resources res : resourcesList) {
					// 打包
					// 获取此资源文件的数据字典信息
					int fileIndex = DictUtil.dict("projectFileName", res.getFunctionFlog() + "").getDisSort();// 排序值
					// 获取文件服务器真实路径
					String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
					String filePath = request.getSession().getServletContext().getRealPath("/");
					fileRealPath = filePath + "file_resource" + fileRealPath;
					// 文件上传的真实名
					fileNameList.add(fileIndex + "-" + res.getOldName());
					File file = new File(fileRealPath);
					fileList.add(file);
				}
			}
		}

		// 1.4、获取质疑投诉资料
		if (resIdsList.contains(OPPUGN_PAUSE)) {
			List<WebContent> webContentList = this.webContentService.findListByProjectId(project.getId());
			for (WebContent web : webContentList) {
				List<Resources> resourcesList = FileResUtil.findResources(web.getId());
				for (Resources res : resourcesList) {
					// 获取此资源文件的数据字典信息
					int fileIndex = DictUtil.dict("projectFileName", res.getFunctionFlog() + "").getDisSort();// 排序值
					// 打包
					// 获取文件服务器真实路径
					if (OPPUGN_PAUSE.equals(res.getFunctionFlog().toString())) {// 质疑投诉资料
						String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
						String filePath = request.getSession().getServletContext().getRealPath("/");
						fileRealPath = filePath + "file_resource" + fileRealPath;
						// 文件上传的真实名
						fileNameList.add(fileIndex + "-" + res.getOldName());
						File file = new File(fileRealPath);
						fileList.add(file);
					}
				}
			}
		}
		// 1.5、获取变更公告资料
		if (resIdsList.contains(EDITPUBLISH)) {
			List<WebContent> webContentList = this.webContentService.findListByProjectId(project.getId());
			for (WebContent web : webContentList) {
				List<Resources> resourcesList = FileResUtil.findResources(web.getId());
				for (Resources res : resourcesList) {
					// 获取此资源文件的数据字典信息
					int fileIndex = DictUtil.dict("projectFileName", res.getFunctionFlog() + "").getDisSort();// 排序值
					// 打包
					// 获取文件服务器真实路径
					if (EDITPUBLISH.equals(res.getFunctionFlog().toString())) {// 变更公告
						String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
						String filePath = request.getSession().getServletContext().getRealPath("/");
						fileRealPath = filePath + "file_resource" + fileRealPath;
						// 文件上传的真实名
						fileNameList.add(fileIndex + "-" + res.getOldName());
						File file = new File(fileRealPath);
						fileList.add(file);
					}
				}
			}
		}

		// 2、获取投标人资料
		if (bidderIds != null) {
			for (String bidderId : bidderIds) {
				List<Resources> bidderResList = FileResUtil.findResources(projectId + "," + bidderId);
				RegisterUser registerUser = this.projectInfoService.get(RegisterUser.class, bidderId);
				List<File> bidderFileList = new ArrayList<File>();
				List<String> bidderFileNameList = new ArrayList<String>();
				for (Resources res : bidderResList) {
					// 打包
					// 获取文件服务器真实路径
					String fileRealPath = res.getFilePath() + File.separator + res.getId() + res.getExeName();
					String filePath = request.getSession().getServletContext().getRealPath("/");
					fileRealPath = filePath + "file_resource" + fileRealPath;
					// 文件上传的真实名
					bidderFileNameList.add(res.getOldName());
					File file = new File(fileRealPath);
					bidderFileList.add(file);
				}
				if (registerUser != null) {
					File tempFile = File.createTempFile(registerUser.getLoginName() + System.currentTimeMillis(),
							".zip");// 打包的投标人资料(临时文件,保证文件名长度大于3个)
					// File tempFile = new
					// File("G:/"+registerUser.getLoginName()+".zip");//打包的投标人资料
					ZipArchiveOutputStream zos = new ZipArchiveOutputStream(tempFile);
					// 打包文件
					BatchZipDownload.zip(bidderFileList, bidderFileNameList, "", zos);
					// 将打包的zip加入总包里
					fileList.add(tempFile);
					fileNameList.add(registerUser.getLoginName() + ".zip");
					// 将临时文件存入临时文件集合中
					tenpFileList.add(tempFile);
					if (zos != null) {
						zos.close();
					}
				}
			}

		}

		ZipArchiveOutputStream zos = null;
		OutputStream os = null;
		String zipName = project.getName() + ".zip";
		try {

			zos = new ZipArchiveOutputStream(response.getOutputStream());
			os = response.getOutputStream();

			// 下载
			response.reset();
			response.setHeader("Content-disposition",
					"attachment;filename=\"" + new String(zipName.getBytes("gb2312"), "ISO-8859-1") + "\"");
			response.setContentType("application/octet-stream");
			// response.setHeader("Content_Length", String.valueOf()));

			// String Agent = request.getHeader("User-Agent");
			// Agent = Agent.toLowerCase();
			// if (Agent.indexOf("firefox") != -1) {
			// zipName = new String(zipName.getBytes("utf-8"), "iso8859-1");
			// } else if (Agent.indexOf("msie") != -1) {
			// zipName = java.net.URLEncoder.encode(zipName, "utf-8");
			// } else {
			// zipName = java.net.URLEncoder.encode(zipName, "utf-8");
			// }
			//
			//
			// if (StringUtils.contains(Agent, "msie")) {// IE浏览器
			// zipName = URLEncoder.encode(zipName, "UTF8");
			// } else if (StringUtils.contains(Agent, "mozilla")) {//
			// google,火狐浏览器
			// zipName = new String(zipName.getBytes(), "ISO8859-1");
			// } else {
			// zipName = new String(zipName.getBytes("utf-8"), "iso8859-1");
			// }
			//
			// response.setHeader("Content-Disposition", "attachment; filename="
			// + zipName);
			// response.setContentType("application/octet-stream;
			// charset=utf-8");
			//
			// Agent = Agent.toLowerCase();
			// if (Agent.indexOf("firefox") != -1) {
			// zipName = new String(zipName.getBytes("utf-8"), "iso8859-1");
			// } else if (Agent.indexOf("msie") != -1) {
			// zipName = java.net.URLEncoder.encode(zipName, "utf-8");
			// } else {
			// zipName = java.net.URLEncoder.encode(zipName, "utf-8");
			// }
			// response.setHeader("Content-Disposition", "attachment; filename="
			// + zipName);
			// response.setContentType("application/octet-stream;
			// charset=utf-8");
			// response.addHeader("Pargam", "no-cache");
			// response.addHeader("Cache-Control", "no-cache");

			// 整体打包文件
			BatchZipDownload.zip(fileList, fileNameList, "", zos);

		} catch (Exception e) {
			System.err.println(e);
			} finally {
			if (zos != null) {
				try {
					os.flush();
					zos.flush();
					zos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 删除临时文件
			for (File file : tenpFileList) {
				file.delete();
			}
		}

	}

	/**
	 * @description 中标通知书打印
	 * @author wwang
	 * @date 2016年9月13日
	 * @param session
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/bidder/winbidAlertPrint")
	public ModelAndView winbidAlertPrint(HttpSession session, String projectId) {
		ModelAndView mv = new ModelAndView("/proj/bidder/winbid-alert-print");
		// 项目信息
		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		// 中标的投标信息
		ProjectBidInfo pb = projectInfoService.getProjectBidderByProjIdAndBidderId(project.getId(),
				project.getWinningId());
		// 查询发放中标通知书时间
		mv.addObject("pro", project);
		mv.addObject("pb", pb);
		return mv;
	}

	/**
	 * @description 评审表页面
	 * @author shy
	 * @date 2016-9-27
	 */
	@RequestMapping("/print/reviewPage")
	public ModelAndView reviewPage(HttpSession session, String projectId) {
		ModelAndView mv = new ModelAndView("/proj/reviewFile/review");
		mv.addObject("projectId", projectId);
		return mv;
	}

	/**
	 * @description 评审表
	 * @author shy
	 * @throws IOException
	 * @date 2016-9-11
	 */
	@RequestMapping("/print/review")
	@ResponseBody
	public String review(HttpSession session, String projectId, HttpServletRequest request, HttpServletResponse resp)
			throws IOException {
		List<ProjectBidInfo> list = this.projectBidService.getProjectBidByProjectId(projectId);
		ProjectInfo pi = this.projectInfoService.get(ProjectInfo.class, projectId);// 项目信息
		String _responFile = pi.getResponseFile();
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyy年MM月dd日");
		String newDate = sFormat.format(new Date());
		int i = 0;
		StringBuilder sb = new StringBuilder();
		final String htmlModelPath = ProjectBidController.class.getResource("/htmlModel").getPath();
		Map<String, Object> m2 = new HashMap<String, Object>();
		List<String> _l = Arrays.asList(_responFile.replaceAll("-", "").split("@"));
		m2.put("titles", _l);
		String tempModel = "";
		if (list.size() < 1) {// 没有投标人
			// m2.put("tender"+ j, tenderName.getBidderName());
			m2.put("tender1", "");
			m2.put("tender2", "");
			m2.put("tender3", "");
			m2.put("tender4", "");
			m2.put("projectCode", pi.getCode());
			m2.put("projectName", pi.getName());
			m2.put("now", newDate);
			String _modelStr = FileResUtil.fileToString(htmlModelPath + "/auditPage_1.html");
			sb.append(CommUtil.freemarkerProcess(m2, _modelStr));
		} else {
			for (ProjectBidInfo tenderer : list) {
				i++;
				if (i % 4 != 0) {
					int j = i % 4;
					m2.put("tender" + j, tenderer.getBidderName());
					m2.put("projectCode", pi.getCode());
					m2.put("projectName", pi.getName());
					m2.put("now", newDate);
				} else { // 本页的最后一条数据，产生html
					m2.put("tender4", tenderer.getBidderName());
					m2.put("projectCode", pi.getCode());
					m2.put("projectName", pi.getName());
					m2.put("titles", _l);
					if (i <= 4) { // 首页模板
						tempModel = htmlModelPath + "/auditPage_1.html";
					} else { // 加入分隔页
						tempModel = htmlModelPath + "/auditPage_n.html";
					}
					String _tmp = FileResUtil.fileToStringByUTF8(tempModel);
					sb.append(CommUtil.freemarkerProcess(m2, _tmp));
					m2.clear();
				}
			}

			// 如果list不是4的整数，则加入尾部数据
			if (i % 4 != 0 && i > 0) {
				int j = i % 4;
				for (; 4 - j > 0;) {
					j++;
					m2.put("tender" + j, "");
				}
				String str = FileResUtil.fileToString(htmlModelPath + "/auditPage_n.html");
				m2.put("projectCode", pi.getCode());
				m2.put("projectName", pi.getName());
				m2.put("now", newDate);
				m2.put("titles", _l);
				sb.append(CommUtil.freemarkerProcess(m2,
						FileResUtil.fileToStringByUTF8(htmlModelPath + "/auditPage_n.html")));
			}
		}
		return sb.toString();
	}



	/**
	 * @description 进入退还保证金页面
	 * @author shy
	 * @param session
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/leader/returnDepositPage")
	public ModelAndView returnDepositPage(HttpSession session, String projectId) {
		boolean showBidFlag = false;// 是否显示中标保证金明细
		boolean showButtonFlag = false;// 是否显示保证金完成按钮
		ProjectInfo projectInfo = projectInfoService.get(ProjectInfo.class, projectId);
		boolean Bidflag = winningDepositShowByProjectStatus(projectInfo.getStatus());
		ModelAndView mv = new ModelAndView();
		if(projectInfo.getAuditable()==true){//中标
			String winningId = projectInfo.getWinningId();
			boolean ifPayDeposit = isPayDepositReturn(projectInfo);
			if(ifPayDeposit == true){
				showBidFlag = true;
				showButtonFlag =true;
			}
			else if (Bidflag == true && winningId != null) {
				showBidFlag = true;
			}
			if (winningId != null) {// 有中标人
				showButtonFlag = winningDepositShowByProjectStatus(projectInfo.getStatus());
			} else {
				showButtonFlag = true;
			}
			mv.setViewName("/proj/leader/deposit-list");
			mv.addObject("projectId", projectId);
			mv.addObject("isShowBid", showBidFlag);
			mv.addObject("showButtonFlag", showButtonFlag);
		}else{//非中标
			//获取中标单位信息（非评标，多个中标单位）
			List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(projectInfo.getId());
		//查询银行接口，履约保证金缴纳信息
//			List<Bank> bidBondInfoList = depositExecuteService.getDepositList(projectInfo.getId());
//			//判断是否缴纳履约保证金
//			String noBidBondName = getNoBidBondName(bidBondInfoList, bidInfos);
//			Boolean ifPayExcuteDeposit=false;
//			if("".equals(noBidBondName)){
//				ifPayExcuteDeposit=true;
//			}
//			if(ifPayExcuteDeposit==true){
//				showBidFlag = true;
//				showButtonFlag =true;
//			}else
			if (Bidflag == true && !bidInfos.isEmpty() ) {
				showBidFlag = true;
			}
			if (!bidInfos.isEmpty() ) {// 有中标人
				showButtonFlag =Bidflag;
			} else {
				showButtonFlag = true;
			}
			mv.setViewName("/proj/leader/deposit-list-noEvalution");
			mv.addObject("projectId", projectId);
			mv.addObject("isShowBid", showBidFlag);
			mv.addObject("showButtonFlag", showButtonFlag);
		}

		return mv;
	}

	/**
	 * @description 进入保证金明细证金页面
	 * @author shy
	 * @param session
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/leader/returnDepositDetailPage")
	public ModelAndView returnDepositDetail(HttpSession session, String projectId){
		boolean showBidflag=false;
		ProjectInfo projectInfo = projectInfoService.get(ProjectInfo.class, projectId);
		ModelAndView mv = new ModelAndView();
		if(projectInfo.getAuditable()==true){
			String winningId=projectInfo.getWinningId();
			if(winningId!=null){
				showBidflag=true;
			}
			mv.setViewName("/proj/leader/deposit-detail");
			mv.addObject("projectId", projectId);
			mv.addObject("isShowBid", showBidflag);
		}else{
			List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(projectInfo.getId());
			if (!bidInfos.isEmpty()){
				showBidflag=true;
			}
			mv.setViewName("/proj/leader/deposit-detail-noEvaluation");
			mv.addObject("projectId", projectId);
			mv.addObject("isShowBid", showBidflag);
		}


		return mv;
	}

	/**
	 * @description 根据状态显示中标人信息
	 * @author shy
	 * @date 2016年10月28日
	 */
	private boolean winningDepositShowByProjectStatus(Integer status) {
		List<Integer> list = new ArrayList<Integer>();
		list.addAll(Arrays.asList(
				Integer.valueOf(ProjectStatus.WAIT_CONTACT_AUDIT.toString()),
				Integer.valueOf(ProjectStatus.CONTACT_AUDIT_NOT_PASS.toString()),
				Integer.valueOf(ProjectStatus.SHOW_CONTACT.toString()),
				Integer.valueOf(ProjectStatus.SHOW_CONTACT_OVER.toString()),
				Integer.valueOf(ProjectStatus.WAIT_RECEIVING.toString()),
				Integer.valueOf(ProjectStatus.RECEIVING_UNAUTH.toString()),
				Integer.valueOf(ProjectStatus.RECEIVING_SHOWING.toString()),
				Integer.valueOf(ProjectStatus.WAIT_PROJ_OVER_SURE.toString()),
				Integer.valueOf(ProjectStatus.PROJ_OVER.toString())));
		return list.contains(status);
	}

	/**
	 * @description 获取投标人保证金信息列表
	 * @author shy
	 * @param projectId
	 * @param resp
	 * @param page
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping("/leader/getProjectBidList")
	@ResponseBody
	public void getProjectBidList(String projectId, HttpServletResponse resp, Page page, Integer type)
			throws IOException, ParseException {
//		List<ProjectBidInfo> projectBidInfoList = projectBidService.getProjectBidCount(projectId);
		ProjectInfo projectInfo = this.projectInfoService.get(ProjectInfo.class, projectId);
		// 1.获取中标人的信息（中标人的loginName）
		String bidderName = projectInfo.getWinningName();
		// 2.查DepositReturn 表是否有数据，如果没有那么从银行接口获取数据
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
		// if(listDespost.isEmpty()) { //如果 非空则不再取
		List<Bank> bankreturnList = depositService.getDepositList(projectId);
		if (bankreturnList!=null) {
			System.out.println("ProjectBidController.getProjectBidList()-------------->bankreturnList: "+bankreturnList.size());
			for (Bank bank : bankreturnList) {
				ComposeIdPK composeIdPK = new ComposeIdPK();
				composeIdPK.setCompanyName(bank.getInName());
				composeIdPK.setProjectId(projectId);
				composeIdPK.setDepositType(Constant.DEPOSIT_TYPE_BIDDER);
				composeIdPK.setHstSeqNum(bank.getHstSeqNum());//交易流水号
				DepositReturn depositReturn = depositReturnService.get(DepositReturn.class, composeIdPK);
				if (depositReturn == null) {
					depositReturn = new DepositReturn();
					// DepositReturn depositReturn = new DepositReturn();
					RegisterUser rUser=null;
					if(bank.getInName()!=null){
						rUser= registerUserService.getRegisterByLoginname(bank.getInName());
					}
					if (rUser == null) {
						// 未查到相关数据，系统记录与银行数据不一致，记录系统日志，并忽略这条记录
						// 记住修改log表的content为varchar(2000)
						LogInfo log1 = new LogInfo("从银行返回的数据中查找不到用户信息" + bank.getInName(), "", "",
								String.valueOf(LogType.ADD.ordinal()), "ProjectBidController.class", "");
						LogUtil.addLog(log1);
						if(bank.getInName()==null || bank.getInName().equals("")){

							continue;  //不符合条件，不需要写值，直接跳过
						}
						this.saveOutDeposit(bank, projectInfo,Constant.DEPOSIT_TYPE_BIDDER);
						continue;
					}
					if(rUser!=null && !bank.getInAcct().equals(rUser.getAccount())){//系统账号的银行卡号和bank的卡号不一致
						//未查到相关数据，系统记录与银行数据不一致，记录系统日志，并忽略这条记录
				        LogInfo log1= new LogInfo("从银行返回的数据中的银行卡号和注册账号卡号不一致： "+bank.getInName(),"","",
				        		String.valueOf(LogType.ADD.ordinal()), "QuartZAll.class", "");
				        LogUtil.addLog(log1);
						if(bank.getInName()==null || bank.getInName().equals("")){

							continue;  //不符合条件，不需要写值，直接跳过
						}
	    				//如果发现这个用户的系统账号的银行卡号和bank的卡号不一致，调用系统外用户
	    				this.saveOutDeposit(bank, projectInfo,Constant.DEPOSIT_TYPE_BIDDER);
						continue;
					}
					ComposeIdPK composeIdPK2 = new ComposeIdPK();
					composeIdPK2.setCompanyName(bank.getInName());
					composeIdPK2.setProjectId(projectId);
					composeIdPK2.setDepositType(Constant.DEPOSIT_TYPE_BIDDER);
					depositReturn.setBankName(rUser.getBank());
					depositReturn.setProjectType(projectInfo.getCatagoryName());
					depositReturn.setPk(composeIdPK);
					depositReturn.setBidderId(rUser.getId());
					depositReturn.setBiaoDuanNo(projectId); // 标段号
					depositReturn.setProjectName(projectInfo.getName());
					depositReturn.setReturnOpt(0); // 默认为未提交申请
					depositReturn.setStatus(0); // 默认为未退还
					depositReturn.setProjectCode(projectInfo.getCode());
					depositReturn.setTnAmount(new BigDecimal(bank.getInAmount())); // 金额
					depositReturn.setTransTime(simpleDateFormat.parse(bank.getInDate() + bank.getInTime())); // 时间格式：//// 2016-10-19//// 12:10:37
					//depositReturn.setHstSeqNum(bank.getHstSeqNum());
					composeIdPK2.setHstSeqNum(bank.getHstSeqNum());//交易流水号
					depositReturn.setInAcct(bank.getInAcct());
					depositReturn.setIsBid(false); // 默认为未投标
					if(bank.getAddWord()!=null){//获取中间值
						depositReturn.setAddWord(bank.getAddWord());
					}else {
						depositReturn.setAddWord("");
					}

					this.projectBidService.saveOrUpdate(depositReturn);
				} else {
					depositReturn.setTnAmount(new BigDecimal(bank.getInAmount()));
				}
			}
		}
		this.projectBidService.getUnBidDepositReturn(projectId, bidderName, page, type);
		List<DepositReturn> drList = (List<DepositReturn>) page.getResult();
		for (DepositReturn dr : drList) {
             ProjectBidInfo pf = projectInfoService.getProjectBidderByProjIdAndBidderId(projectId, dr.getBidderId());
                if(pf !=null && pf.getFlag()==1){
                	dr.setIsBid(true); // 设置已投标
                }
		}
		JSONObject jsonObject = CommUtil.getPageJSONData(page, true);
		resp.getWriter().print(jsonObject);
	}

	/**
	 * @description 获取投标人保证金信息列表
	 * @author shy
	 * @param projectId
	 * @param resp
	 * @throws IOException
	 * @throws ParseException
	 */
	@RequestMapping("/leader/getProjectBidList_noEvaluation")
	@ResponseBody
	public void getProjectBidList_noEvaluation(String projectId, HttpServletResponse resp, Integer type)
			throws IOException, ParseException {
		ProjectInfo projectInfo = this.projectInfoService.get(ProjectInfo.class, projectId);
		// 2.查DepositReturn 表是否有数据，如果没有那么从银行接口获取数据
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
		// if(listDespost.isEmpty()) { //如果 非空则不再取
		List<Bank> bankreturnList = depositService.getDepositList(projectId);
		if (bankreturnList!=null) {
			System.out.println("ProjectBidController.getProjectBidList()-------------->bankreturnList: "+bankreturnList.size());
			for (Bank bank : bankreturnList) {
				ComposeIdPK composeIdPK = new ComposeIdPK();
				composeIdPK.setCompanyName(bank.getInName());
				composeIdPK.setProjectId(projectId);
				composeIdPK.setDepositType(Constant.DEPOSIT_TYPE_BIDDER);
				composeIdPK.setHstSeqNum(bank.getHstSeqNum());//交易流水号
				DepositReturn depositReturn = depositReturnService.get(DepositReturn.class, composeIdPK);
				if (depositReturn == null) {
					depositReturn = new DepositReturn();
					// DepositReturn depositReturn = new DepositReturn();
					RegisterUser rUser=null;
					if(bank.getInName()!=null){
						rUser= registerUserService.getRegisterByLoginname(bank.getInName());
					}
					if (rUser == null) {
						// 未查到相关数据，系统记录与银行数据不一致，记录系统日志，并忽略这条记录
						// 记住修改log表的content为varchar(2000)
						LogInfo log1 = new LogInfo("从银行返回的数据中查找不到用户信息" + bank.getInName(), "", "",
								String.valueOf(LogType.ADD.ordinal()), "ProjectBidController.class", "");
						LogUtil.addLog(log1);
						if(bank.getInName()==null || bank.getInName().equals("")){

							continue;  //不符合条件，不需要写值，直接跳过
						}
						this.saveOutDeposit(bank, projectInfo,Constant.DEPOSIT_TYPE_BIDDER);
						continue;
					}
					if(rUser!=null && !bank.getInAcct().equals(rUser.getAccount())){//系统账号的银行卡号和bank的卡号不一致
						//未查到相关数据，系统记录与银行数据不一致，记录系统日志，并忽略这条记录
						LogInfo log1= new LogInfo("从银行返回的数据中的银行卡号和注册账号卡号不一致： "+bank.getInName(),"","",
								String.valueOf(LogType.ADD.ordinal()), "QuartZAll.class", "");
						LogUtil.addLog(log1);
						if(bank.getInName()==null || bank.getInName().equals("")){

							continue;  //不符合条件，不需要写值，直接跳过
						}
						//如果发现这个用户的系统账号的银行卡号和bank的卡号不一致，调用系统外用户
						this.saveOutDeposit(bank, projectInfo,Constant.DEPOSIT_TYPE_BIDDER);
						continue;
					}
					ComposeIdPK composeIdPK2 = new ComposeIdPK();
					composeIdPK2.setCompanyName(bank.getInName());
					composeIdPK2.setProjectId(projectId);
					composeIdPK2.setDepositType(Constant.DEPOSIT_TYPE_BIDDER);
					depositReturn.setBankName(rUser.getBank());
					depositReturn.setProjectType(projectInfo.getCatagoryName());
					depositReturn.setPk(composeIdPK);
					depositReturn.setBidderId(rUser.getId());
					depositReturn.setBiaoDuanNo(projectId); // 标段号
					depositReturn.setProjectName(projectInfo.getName());
					depositReturn.setReturnOpt(0); // 默认为未提交申请
					depositReturn.setStatus(0); // 默认为未退还
					depositReturn.setProjectCode(projectInfo.getCode());
					depositReturn.setTnAmount(new BigDecimal(bank.getInAmount())); // 金额
					depositReturn.setTransTime(simpleDateFormat.parse(bank.getInDate() + bank.getInTime())); // 时间格式：//// 2016-10-19//// 12:10:37
					//depositReturn.setHstSeqNum(bank.getHstSeqNum());
					composeIdPK2.setHstSeqNum(bank.getHstSeqNum());//交易流水号
					depositReturn.setInAcct(bank.getInAcct());
					depositReturn.setIsBid(false); // 默认为未投标
					if(bank.getAddWord()!=null){//获取中间值
						depositReturn.setAddWord(bank.getAddWord());
					}else {
						depositReturn.setAddWord("");
					}

					this.projectBidService.saveOrUpdate(depositReturn);
				} else {
					depositReturn.setTnAmount(new BigDecimal(bank.getInAmount()));
				}
			}
		}
		List<DepositReturn> drList =  this.projectBidService.getDepositReturnNoEvaluation(projectId,type);
		//获取中标单位信息（非评标，多个中标单位）
		List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(projectInfo.getId());
		//构建数组（中标信息）
		ArrayList bidIds=new ArrayList();
		for(ProjectBidInfo bf:bidInfos){
			bidIds.add(bf.getUserId());
		}
		List<DepositReturn> bidList=new ArrayList<DepositReturn>();//中标人列表
		List<DepositReturn> unbidList=new ArrayList<DepositReturn>();//非中标人列表
		if(!bidInfos.isEmpty()){//中标人不为空
			for(DepositReturn d:drList){
				ProjectBidInfo pf = projectInfoService.getProjectBidderByProjIdAndBidderId(projectId, d.getBidderId());
				//判断是否投标
				if(pf !=null && pf.getFlag()==1){
					d.setIsBid(true); // 设置已投标
				}
				boolean isContains =bidIds.contains(d.getBidderId());
				//区分中标或非中标保证金
				if(isContains==true){
					bidList.add(d);
				}else{
					unbidList.add(d);
				}
			}
		}else{//中标人为空
			for(DepositReturn d:drList){
				ProjectBidInfo pf = projectInfoService.getProjectBidderByProjIdAndBidderId(projectId, d.getBidderId());
				//判断是否投标
				if(pf !=null && pf.getFlag()==1){
					d.setIsBid(true); // 设置已投标
				}
				unbidList.add(d);
			}
		}
       //  根据请求类型返回中标或者非中标保证金类型
		if(type==0){
			DateJsonValueProcessor processor = new DateJsonValueProcessor();
			DateJsonValueProcessor dateProcessor = new DateJsonValueProcessor("yyyy-MM-dd HHmmss");
			JsonConfig config = new JsonConfig();
			config.registerJsonValueProcessor(Date.class, processor);
			config.registerJsonValueProcessor(java.sql.Date.class, dateProcessor);
			resp.getWriter().print(JSONArray.fromObject(unbidList,config));
		}else if(type==1){
			DateJsonValueProcessor processor = new DateJsonValueProcessor();
			DateJsonValueProcessor dateProcessor = new DateJsonValueProcessor("yyyy-MM-dd HHmmss");
			JsonConfig config = new JsonConfig();
			config.registerJsonValueProcessor(Date.class, processor);
			config.registerJsonValueProcessor(java.sql.Date.class, dateProcessor);
			resp.getWriter().print(JSONArray.fromObject(bidList,config));
		}
	}

	/**
     * 保存系统外用户保证金信息
     */
    private void saveOutDeposit(Bank bank,ProjectInfo proj,int depositType){
    	//组装
    	ComposeIdPK2 pk= new ComposeIdPK2();
    	pk.setCompanyName(bank.getInName());
    	pk.setHstSeqNum(bank.getHstSeqNum());
    	pk.setProjectId(proj.getId());
    	pk.setDepositType(depositType);
    	//查询数据库中是否有此信息
    	DepositReturnOut depositReturn=depositReturnService.get(DepositReturnOut.class, pk);
    	if(depositReturn==null){
    		depositReturn= new DepositReturnOut();
    		depositReturn.setReturnOpt(0);// 默认为未提交申请
    		depositReturn.setStatus(0);// 默认为未退还
    	}

    	depositReturn.setPk(pk);
    	depositReturn.setProjectType(proj.getCatagoryName());
    	depositReturn.setBiaoDuanNo(proj.getId());// 标段号
		depositReturn.setProjectName(proj.getName());
		depositReturn.setProjectCode(proj.getCode());
		depositReturn.setTnAmount(new BigDecimal(bank.getInAmount()));
		depositReturn.setBankName(bank.getInName());
		String date ="";
    	SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyyMMddhhmmss");
		date = bank.getInDate() + bank.getInTime(); // 拼接日期
		try {
			depositReturn.setTransTime(simpleDateFormat.parse(date));//缴费时间
		} catch (ParseException e) {
			e.printStackTrace();
		}// 时间
		depositReturn.setInAcct(bank.getInAcct());
		depositReturn.setBid(false);	// 默认为未投标
		depositReturn.setAddWord(bank.getAddWord());

    	depositReturnService.saveOrUpdate(depositReturn);
    }

	/**
	 * @description 退还保证金
	 * @author shy
	 * @return
	 */
	@RequestMapping("/leader/returnDeposit")
	@ResponseBody
	@Transactional
	public String returnDeposit(String projectId, String projectName,  String bidderId,String hstSeqNum) {
		String bidderName="";
		String result="";
		//获取biddername;
		ComposeIdPK pk = new ComposeIdPK();
		bidderName=this.registerUserService.get(RegisterUser.class,bidderId).getLoginName();
		pk.setCompanyName(bidderName);
		pk.setHstSeqNum(hstSeqNum);
		pk.setProjectId(projectId);
		pk.setDepositType(0);
		//DepositReturn depositReturn = depositReturnService.getDepositReturn(bidderName,projectId);
		DepositReturn depositReturn = depositReturnService.get(DepositReturn.class, pk);
		ProjectInfo projectInfo = this.projectInfoService.get(ProjectInfo.class, projectId);
		if(projectInfo.getAuditable()==true){
			if(bidderId.equals(projectInfo.getWinningId())){
				 List<DepositReturn> executeDeposit = this.depositReturnService.getExcuteDeposit(projectId, bidderId,Constant.DEPOSIT_TYPE_EXECUTE);
				 if(executeDeposit.isEmpty()){
					 return Constant.NO_EXECTUE_DEPOSIT;
				 }
			  }
		  }else{
			//获取中标单位信息（非评标，多个中标单位）
			List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(projectInfo.getId());
			for(ProjectBidInfo bInfo :bidInfos){
				//判断中标人是否缴纳履约保证金
				if(bidderId.equals(bInfo.getUserId())){
					List<DepositReturn> executeDeposit = this.depositReturnService.getExcuteDeposit(projectId, bidderId,Constant.DEPOSIT_TYPE_EXECUTE);
					if(executeDeposit.isEmpty()){
						return Constant.NO_EXECTUE_DEPOSIT;
					}
				}
			}
		}

		//设置延迟
	    final ExecutorService exec = Executors.newFixedThreadPool(1);
	    try {
	        Future<String> future = exec.submit(new BankResult(projectId,projectName,bidderName,bidderId,pk));
	        Integer bankResult =Integer.parseInt(future.get(8000, TimeUnit.MILLISECONDS)); //设置8秒
	        if(bankResult==1){
	        	 depositReturn.setReturnOpt(1);//银行返回1 申请退还成功
				 this.depositReturnService.saveOrUpdate(depositReturn);
				 result= Constant.SAVE_SUCCESS;
	        }else if(bankResult==0){//银行返回0 申请退还失败
	        	 depositReturn.setReturnOpt(2);
				 this.depositReturnService.saveOrUpdate(depositReturn);
				 result= Constant.SAVE_UN_SUCCESS;
	        }
	        System.out.println("银行回调成功....");
	    } catch (Exception e) {
	    	 depositReturn.setReturnOpt(-1);//超时未返回
			 this.depositReturnService.saveOrUpdate(depositReturn);
	        System.out.println("银行回调超时....");
	        result= Constant.BANK_TIME_OUT;
	    }
	    exec.shutdown();
	    return result;
 	}


	class BankResult implements Callable<String> {
	    private String projectId;
	    private String projectName;
	    private String bidderName;
	    private String bidderId;
	    private ComposeIdPK pk;

	    public BankResult(String projectId,String projectName,String bidderName,String bidderId,ComposeIdPK pk) {
	        this.projectId=projectId;
	        this.bidderName=bidderName;
	        this.projectName=projectName;
	        this.bidderId=bidderId;
	        this.pk=pk;
	    }

	    @Override
	    public String call() throws Exception {
	    	int result = depositService.returnDepositByProj(bidderId, projectId, bidderName, projectName, pk);
	        return String.valueOf(result);
	    }
	}


	/**
	 * @description 根据projectId 获取所有退还保证金信息
	 * @author shy
	 * @param projectId
	 */
	@RequestMapping("/leader/getReturnList")
	@ResponseBody
	public String getReturnList(String projectId,int depositType){
		String result="";
		List<DepositReturn> list =this.depositReturnService.getReturnList(projectId,depositType);
		for(DepositReturn depositReturn:list){
			if(depositReturn.getReturnOpt()==1 && depositReturn.getStatus()== Constant.DEPOSIT_UN_RETURN ){ //已提交，未退还
				result = Constant.UN_PASS;
				return result;
			  }
			}
		for(DepositReturn depositReturn:list){
			if(depositReturn.getReturnOpt()==1 && depositReturn.getStatus()==Constant.FAILE_RETURN){ //已提交，退还不成功
				result = Constant.UN_ALL_RERURN;
				return result;
					 }
					}

		for(DepositReturn depositReturn:list){
			if(depositReturn.getReturnOpt()==2 ||depositReturn.getReturnOpt()==0 ||depositReturn.getReturnOpt()==-1){
				result = Constant.UN_ALL_RERURN;
				return result;
			  }
			}


		return result = Constant.ALL_RERURN;
	}

	/**
	 * @description 完成保证金操作
	 * @author shy
	 * @return
	 */
	@RequestMapping("/leader/finishDepositReturn")
	@ResponseBody
	public String finishDepositReturn(String projectId,int depositType) {
		ProjectInfo projectInfo = this.projectInfoService.get(ProjectInfo.class, projectId);
		List<DepositReturn> UnOptList = this.depositReturnService.getUnOptList(projectId,depositType);
		if (!UnOptList.isEmpty()) {
			for (DepositReturn depositReturn : UnOptList) {
				depositReturn.setStatus(2);
				depositReturn.setUpdateTime(new Date());
				this.depositReturnService.saveOrUpdate(depositReturn);
			}
		}
		if(depositType==0){
			projectInfo.setReturnDepositFlag(true);
		}else if(depositType==1){
			projectInfo.setFinishExecuteDesposit(1);
		}

		this.projectInfoService.saveOrUpdate(projectInfo);

		return Constant.SAVE_SUCCESS;
	}


	/**
	 * @description 进入终止页面
	 * @author shy
	 */
	@RequestMapping("/bizmanager/canclePage")
	public ModelAndView canclePage(HttpSession session, String projectId) {
		ModelAndView mv = new ModelAndView("/proj/bizmanager/projectBit-cancle");
		mv.addObject("projectId", projectId);
		return mv;
	}

	/**
	 * @description 终止项目进程
	 * @author shy
	 */
	@RequestMapping("/bizmanager/closeProject")
	@ResponseBody
	public String closeProject(HttpSession session, String projectId, String budgetMenuData, String cancelReason,Integer status) {
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, projectId);
		ProjectBidInfo pbInfo = new ProjectBidInfo();
		pbInfo.setProjectId(projectId);
		pro.setStatus(status);// 状态显示为撤销或者流标
		if(pro.getAuditable()){//评标项目
			pro.setWinningId(null);
			pro.setWinningName(null);
		}else{//非评标项目
			List<ProjectBidInfo> bidList = this.projectInfoService.findProjectBidListByProjectId(null, pbInfo);
			for (ProjectBidInfo pb : bidList) {
				if(pb.getIsMultHit()){
					pb.setIsMultHit(false);//取消中标单位
					this.projectBidService.saveOrUpdate(pb);
				}
			}
		}
		
		pro.setTradeTime(new Date());//交易时间
		pro.setCancelReason(cancelReason);// 撤销理由
		// this.workflowProcessInstanceService.deleteProcesssInsatance(pro.getWorkflowId(),
		// cancelReason);
		this.workflowProcessInstanceService.suspendProcess(pro.getWorkflowId());
		this.projectInfoService.saveOrUpdate(pro);
		// 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(pro.getId());
					res.setFunctionFlog(status);
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}

		return Constant.DEL_SUCCESS;
	}

	/**
	 * @description 质疑/投诉/答复/处理结果 页面
	 * @author wwang
	 * @date 2016年9月18日
	 * @param id
	 * @return
	 */
	@RequestMapping("/leader/oppugnInput")
	public ModelAndView oppugnInput(String id) {
		ModelAndView mv = new ModelAndView("/proj/leader/proj-oppugn-input");
		mv.addObject("projectId", id);
		return mv;
	}

	/**
	 * @description投标人投标资格校验
	 * @author wwang
	 * @date 2016年9月20日
	 * @param projectId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/bidder/bidValidate")
	@ResponseBody
	public String bidValidate(HttpSession session, String projectId) throws Exception {
		User user = (User) session.getAttribute("loginUser");
		RegisterUser registerUser = this.projectInfoService.get(RegisterUser.class, user.getRegisterId());

		ProjectInfo project = this.projectInfoService.get(ProjectInfo.class, projectId);
		//封存用户不能投标
		if(registerUser.getRemoveFlag()==2){
			return Constant.SEALUP_NOBID;
		}
		// 判断是否已经投过标了
		boolean isBid = projectInfoService.isBidByProjIdAndBidderId(project.getId(), registerUser.getId());
		if (isBid) {
			return Constant.EXIT_BID;
		}

		// 1、禁投校验
		if (registerUser.getForbidStartDate() != null) {
			Date forbidStartDate = registerUser.getForbidStartDate();// 禁投开始日期
			Date forbidEndDate = registerUser.getForbidEndDate();// 禁投结束日期
			if (forbidStartDate != null && forbidEndDate != null && forbidEndDate.compareTo(new Date()) >= 0) {// 禁投结束日期大于当前日期
				return Constant.PROJECT_NO_BID_SAVE_UNSUCCESS;
			}
		}

		// 2、保证金缴纳校验
		// 2.1 判读是否为该项目类型的注册账号
		String registerCategory = this.registerUserService.getDepositCategoryName(registerUser.getId());
		if (!registerCategory.contains(project.getCatagoryName()) && project.getPromissMoney() != 0) {// 保证金为0，不需要缴纳
			return Constant.NO_REG_QUALIFICA_BID;
		}

		// 2.2 判断是否缴纳协议保证金
		String depositCategory = this.registerUserService.getDepositCategory(registerUser.getId());
		if (!depositCategory.contains(project.getCatagoryId()) && project.getPromissMoney() != 0) {// 保证金为0，不需要缴纳
			// 2.3 判断是否缴纳单项保证金
			int ifPaySingleDeposit = depositService.ifPaySingleDeposit(registerUser.getId(), project.getId(),
					registerUser.getLoginName(), project.getName());
			System.out.println("===========ifPaySingleDeposit!=1&&project.getPromissMoney()!=0: "
					+ (ifPaySingleDeposit != 1 && project.getPromissMoney() != 0));
			System.out.println("========================ifPaySingleDeposit: " + ifPaySingleDeposit);
			System.out.println("========================project.getPromissMoney(): " + project.getPromissMoney());
			if (ifPaySingleDeposit != 1 && project.getPromissMoney() != 0) {// 保证金为0，不需要缴纳//已交为1,未交为0,错误为 -1
				if(ifPaySingleDeposit==5){//银行户名或开户行与系统帐户名或开户行不一致
					return Constant.ATYPISM;
				}
				return Constant.NO_QUALIFICA_BID;
			}
		}

		return Constant.SUCCESS;
	}

	/**
	 * @desccription 采购合同下载
	 * @param response
	 * @param request
	 */
	@RequestMapping("/purchasingContract")
	public void uploadPurchasingContract(HttpServletResponse response, HttpServletRequest request) {
		String filePath = request.getSession().getServletContext().getRealPath("/");
		String fileRealPath = filePath + "file_resource/采购合同.doc";

		// 下载文件
		FileDownload.processDownload(fileRealPath, "采购合同.doc", request, response);
	}

	/**
	 * @description打开系统管理员变更项目编号页面
	 * @author wwang
	 * @date 2016年9月18日
	 * @return
	 */
	@RequestMapping("/bizmanager/projectCodeInput")
	public ModelAndView projectCodeInput(String projectId) {
		ModelAndView mv = new ModelAndView("/proj/sysmanager/project-code-input");
		ProjectInfo project = projectInfoService.get(ProjectInfo.class, projectId);
		mv.addObject("project", project);
		return mv;
	}

	/**
	 * @description 业务管理员变更项目编号页面
	 * @param project
	 * @return
	 */
	@RequestMapping("/bizmanager/doSubmitProjectCode")
	@ResponseBody
	public String doSubmitEvaluatePass(ProjectInfo project) {
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, project.getId());
		boolean isExit = validateUniqueService.unique("t_proj_info", "code", project.getCode(), "");
		if (!isExit) {
			return "codeexit";
		}
		pro.setCode(project.getCode());
		this.projectInfoService.saveOrUpdate(pro);
		return Constant.SUCCESS;
	}

	/**
	 * 变更公告页面
	 *
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/leader/editPublish")
	public ModelAndView editPublish(String projectId) {
		ModelAndView mv = new ModelAndView("/proj/leader/editPublish-input");
		ProjectInfo project = projectInfoService.get(ProjectInfo.class, projectId);
		DataSet dataset = projectInfoService.get(DataSet.class, Constant.DATASET_ID);
		mv.addObject("project", project);
		mv.addObject("dataset", dataset);
		return mv;
	}

	/**
	 * 验收报告打印
	 *
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/printReceivinReport")
	public ModelAndView printReceivinReport(String projectId) {
		ModelAndView mv = new ModelAndView("/proj/public/project-receivin-report");
		ProjectInfo project = projectInfoService.get(ProjectInfo.class, projectId);
		mv.addObject("project", project);
		ProjectBidInfo bidInfo = this.projectInfoService.getProjectBidderByProjIdAndBidderId(projectId,
				project.getWinningId());
		mv.addObject("bidInfo", bidInfo);
		return mv;
	}

	/**
	 * @description 同一天，同一时间仅允许2个项目开标
	 * @author shy
	 */
	@RequestMapping("/bidDateVerify")
	@ResponseBody
	public boolean bidDateVerify(Date date) {
		boolean flag = true;
		DataSet dataset = this.projectInfoService.get(DataSet.class, Constant.DATASET_ID);
		int evaluateRooms = dataset.getEvaluateRooms();
		int projectCount = this.projectBidService.getProjectCount(date);
		if (projectCount >= evaluateRooms) {
			flag = false;
		}
		return flag;
	}

	/**
	 * @description 是否为工作日,且超过三个工作日
	 * @author shy
	 * @throws Exception
	 */
	@RequestMapping("/isWorkDay")
	@ResponseBody
	public boolean isWorkDay(Date date, Date validTime) throws Exception {
		boolean flag = true;
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
		Calendar calStart = Calendar.getInstance();
		calStart.setTime(date);
		List<String> dates = this.holidaySetServiceImpl.findAllByYear(calStart.get(Calendar.YEAR)+"");
		if (dates.contains(sdf1.format(calStart.getTime()))) {
			flag = false;
		} else {
			//采购确认时间
			Calendar cd = Calendar.getInstance();
			cd.setTime(validTime);
			cd.add(Calendar.DATE, 1);// 增加天数
			String validTimeStr=sdf1.format(cd.getTime())+" 00:00:00";

			//开标时间
			Calendar cdBid = Calendar.getInstance();
			cdBid.setTime(sdf1.parse(validTimeStr));

			//相隔天数
			long betweenDay = (calStart.getTime().getTime()-cdBid.getTime().getTime())/(1000*3600*24);
			int index=0;
			while(betweenDay+1>0){
				if (!dates.contains(sdf1.format(calStart.getTime()))) {
					index++;
				}
				calStart.add(Calendar.DAY_OF_YEAR, -1);
				betweenDay--;
			}
			if(index<=3){//超过三天
				flag=false;
			}
		}
		return flag;
	}

	/**
	 * @description 是否为工作日
	 * @author shy
	 * @throws Exception
	 */
	@RequestMapping("/isWorkDayToShot")
	@ResponseBody
	public boolean isWorkDayToShot(Date date) throws Exception {
		boolean flag = true;
		if(date==null){
			return false;
		}
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
		Calendar calStart = Calendar.getInstance();
		calStart.setTime(date);
		List<String> dates = this.holidaySetServiceImpl.findAllByYear(sdf2.format(date));
		if (dates.contains(sdf1.format(calStart.getTime()))) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 原开标项目编号搜索自动完成
	 *
	 * @return
	 */
	@RequestMapping("/comboList")
	@ResponseBody
	public JSONArray comboList() {
		List<Combo> comboList = new ArrayList<>();
		List<ProjectInfo> projectList = this.projectBidService.getProjectCodeCombo();
		for (ProjectInfo project : projectList) {
			Combo combo = new Combo();
			combo.setId(project.getId());
			combo.setText(project.getCode());
			combo.setSpell(project.getCode());
			comboList.add(combo);
		}
		return JSONArray.fromObject(comboList);
	}

	/**
	 * @description 评标补录资料 页面
	 * @author wwang
	 * @date 2016年9月5日
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/leader/makeFileInput")
	@ResponseBody
	public ModelAndView makeFileInput(String projectId) {
		ModelAndView mv = new ModelAndView("/proj/leader/makeup-file-input");
		// 项目信息
		ProjectInfo project = projectInfoService.get(ProjectInfo.class, projectId);
		mv.addObject("project", project);
		// 附件
		if (!StringUtil.isEmpty(projectId)) {
			List<Resources> resList = FileResUtil.findResources(projectId);
			mv.addObject("resList", resList);
		}
		return mv;
	}

	/**
	 * @description 提交评标补录资料
	 * @author wwang
	 * @date 2016年9月5日
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/leader/doSubmitmakeFile")
	@ResponseBody
	public String doSubmitmakeFile(ProjectInfo project, Integer showEndDay, String budgetMenuData) throws Exception {
		// 项目信息
		ProjectInfo pro = projectInfoService.get(ProjectInfo.class, project.getId());
		// 保存补录的 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(pro.getId());
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}
		this.projectInfoService.saveOrUpdate(pro);
		return Constant.SUCCESS;
	}

	/**
	 * @description 查看结果(采购人查看中标流标公告)
	 * @author wwang
	 * @date 2016年9月5日
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/buyer/viewNotifyResult")
	@ResponseBody
	public ModelAndView viewNotifyResult(String projectId) {
		ModelAndView mv = new ModelAndView("/proj/buyer/notifyResult");
		ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(projectId).singleResult();
		String webId=(String) runtimeService.getVariable(process.getId(), "documentId");
		WebContent webcontent = this.webContentService.get(WebContent.class, webId);
		mv.addObject("webcontent",webcontent);
		return mv;
	}


	/**
	 * 投标人撤销投标
	 * @param session
	 * @param projectId
	 * @param projectBidInfo
	 * @return
	 */
	@RequestMapping("/bidder/cancelShot")
	@ResponseBody
	public String cancelShot(HttpSession session,String projectId,ProjectBidInfo projectBidInfo){
		User user = (User) session.getAttribute("loginUser");
		ProjectInfo pro=this.projectInfoService.get(ProjectInfo.class, projectId);
		if(new Date().compareTo(pro.getBidStartTime()) > 0){//到了开标时间(当前时间大于开标时间)
			return Constant.UNSUCCESS;
		}
		RegisterUser registerUser = this.projectInfoService.get(RegisterUser.class, user.getRegisterId());
		// 投标信息
		ProjectBidInfo pb = projectInfoService.getProjectBidderByProjIdAndBidderId(projectId, registerUser.getId());
		pb.setFlag(0);//改为未提交状态
		this.projectInfoService.saveOrUpdate(pb);
		return Constant.SUCCESS;
	}


	/**
	 * @description 进入履约保证金金页面
	 * @author shy
	 * @date 2016-12-23
	 */
	@RequestMapping("/finance/excuteDepositPage")
	@ResponseBody
	public ModelAndView excuteDepositPage(HttpSession session, String projectId) {
		boolean showReturnFlag = false;// 是否显示保证金完成按钮
		ProjectInfo projectInfo = projectInfoService.get(ProjectInfo.class, projectId);
	//	List<DepositReturn> dReturn = this.depositReturnService.getExcuteDeposit(projectId, projectInfo.getWinningId(),Constant.DEPOSIT_TYPE_EXECUTE);
		if(projectInfo.getFinishExecuteDesposit()==0){
			showReturnFlag = excuteDepositButtionByProjectStatus(projectInfo.getStatus());
		}
		ModelAndView mv = new ModelAndView("/proj/leader/excute-deposit-list");
		mv.addObject("projectId", projectId);
		mv.addObject("showButtonFlag", showReturnFlag);
		mv.addObject("bidderId", projectInfo.getWinningId());
		return mv;
    }

	/**
	 * @description  判断退还履约保证按钮出现状态是否在列举的状态中存在
	 * @author shy
	 * @date 2016年12月23日
	 */
	   private boolean excuteDepositButtionByProjectStatus(Integer status) {
		List<Integer> list = new ArrayList<Integer>();
		list.addAll(Arrays.asList(
				Integer.valueOf(ProjectStatus.WAIT_PROJ_OVER_SURE.toString()),//结项
				Integer.valueOf(ProjectStatus.PROJ_OVER.toString()),//项目结束
				Integer.valueOf(ProjectStatus.CANCEL.toString())));//撤销
		return list.contains(status);
		}

	/**
	 * @Description 获取项目履约保证金信息
	 * @author shy
	 * @throws ParseException
	 * @date 2016-12-26
	 */
	  @RequestMapping("finance/getExscuteDeposit")
	  @ResponseBody
	public JSONObject getExscuteDeposit(HttpSession session, String projectId,Page page) throws ParseException{
		  ProjectInfo projectInfo = projectInfoService.get(ProjectInfo.class, projectId);
			  //获取履约保证金信息
			  depositReturnService.getExcuteDepositList(projectId,Constant.DEPOSIT_TYPE_EXECUTE,page);
			  List<DepositReturn> listPage = (List<DepositReturn>)page.getResult();
			  for(DepositReturn dr :listPage){
				  dr.setIsBid(true); // 设置已投标
			  }
		  return CommUtil.getPageJSONData(page, true);

	  }


		/**
		 * @description 退还履约保证金
		 * @author shy
		 * @return
		 */
		@RequestMapping("/finance/returnExecuteDeposit")
		@ResponseBody
		@Transactional
		public String returnExecuteDeposit(String projectId, String projectName,  String bidderId,String hstSeqNum) {
			String result="";
			String bidderName="";
			//获取biddername;
			  bidderName=this.registerUserService.get(RegisterUser.class,bidderId).getLoginName();
			  ComposeIdPK pk =new ComposeIdPK();
			  pk.setDepositType(Constant.DEPOSIT_TYPE_EXECUTE);
			  pk.setHstSeqNum(hstSeqNum);
			  pk.setProjectId(projectId);
			  pk.setCompanyName(bidderName);
			//DepositReturn depositReturn = this.depositReturnService.getExcuteDeposit(projectId, bidderId,Constant.DEPOSIT_TYPE_EXECUTE);
			  DepositReturn depositReturn = this.depositReturnService.get(DepositReturn.class, pk);
			  if(depositReturn.getStatus()==Constant.DEPOSIT_RETURN){
				  return  String.valueOf(Constant.DEPOSIT_RETURN);
			  }else if(depositReturn.getStatus()==Constant.DEPOSIT_DEDUCT){
				  return  String.valueOf(Constant.DEPOSIT_DEDUCT);
			  }
			//设置延迟
		    final ExecutorService exec = Executors.newFixedThreadPool(1);
		    try {
		        Future<String> future = exec.submit(new ExecuteDepositBankResult(projectId,projectName,bidderName,bidderId,pk));
		        Integer bankResult =Integer.parseInt(future.get(8000, TimeUnit.MILLISECONDS)); //设置8秒
		        if(bankResult==1){
		        	 depositReturn.setReturnOpt(1);//银行返回1 申请退还成功
					 this.depositReturnService.saveOrUpdate(depositReturn);
					 result=Constant.SAVE_SUCCESS;
		        }else if(bankResult==0){//银行返回0 申请退还失败
		        	 depositReturn.setReturnOpt(2);
					 this.depositReturnService.saveOrUpdate(depositReturn);
					 result=Constant.SAVE_UN_SUCCESS;
		        }
		        System.out.println("银行回调成功....");
		    }catch (Exception e) {
		    	 depositReturn.setReturnOpt(-1);//超时未返回
				 this.depositReturnService.saveOrUpdate(depositReturn);
				 result=Constant.BANK_TIME_OUT;
		        System.out.println("银行回调超时....");
		    }
		    exec.shutdown();
		    return result;
	 	}

		class ExecuteDepositBankResult implements Callable<String> {
		    private String projectId;
		    private String projectName;
		    private String bidderName;
		    private String bidderId;
		    private ComposeIdPK pk;
		    public ExecuteDepositBankResult(String projectId,String projectName,String bidderName,String bidderId,ComposeIdPK pk) {
		        this.projectId=projectId;
		        this.bidderName=bidderName;
		        this.projectName=projectName;
		        this.bidderId=bidderId;
		        this.pk=pk;
		    }

		    @Override
		    public String call() throws Exception {
		    	int result = executeDepositService.sendReturnDeposit(bidderId, projectId, bidderName, projectName,pk);
		        return String.valueOf(result);
		    }
		}

	/**
	 * 采购确认校验，当前时间不能超过16:30
	 *
	 * @return
	 */
	@RequestMapping("/buyer/validateBuySure")
	@ResponseBody
	public Boolean validateBuySure() {
		String nowStr = DateUtils.simpleDateFormat(new Date(), "yyyy-MM-dd");
		Date validateTime = DateUtils.simpleDateFormat(nowStr + " 16:30:00", "yyyy-MM-dd HH:mm:ss");
		if (new Date().getTime() >= validateTime.getTime()) {
			return false;
		}

		return true;
	}

	/**
	 * 采购创建项目校验，30天内中不能存在相同的项目名
	 *
	 * @return
	 */
	@RequestMapping("/buyer/validProjName")
	@ResponseBody
	public Boolean validProjName(ProjectInfo project) {
		//30天前
		Date validTime = StringUtil.addOneDayDate(new Date(), -30);
		String validTimeStr = DateUtils.simpleDateFormat(validTime, "yyyy-MM-dd");
		validTime = DateUtils.simpleDateFormat(validTimeStr + " 00:00:00", "yyyy-MM-dd HH:mm:ss");

		//当前时间
		String nowTimeStr = DateUtils.simpleDateFormat(new Date() , "yyyy-MM-dd");
		Date nowTime = DateUtils.simpleDateFormat(nowTimeStr + " 23:59:59", "yyyy-MM-dd HH:mm:ss");


		List<ProjectInfo> projectList = this.projectBidService.findListByWhere(project,validTime, nowTime);
		if(projectList!=null&&projectList.size()>=1){
			return false;
		}

		return true;
	}

	/**
	 * 校验中标人履约保证金是否缴纳
	 *
	 * @return
	 */
	@RequestMapping("/public/validBidBond")
	@ResponseBody
	public Boolean validBidBond(ProjectInfo project) {
		project = projectInfoService.get(ProjectInfo.class, project.getId());
		//查询银行接口，履约保证金缴纳信息
		List<Bank> bidBondInfoList = depositExecuteService.getDepositList(project.getId());
		RegisterUser ruser = this.registerUserService.get(RegisterUser.class,project.getWinningId());
		if(ruser!=null){
			DepositReturn bidBondInfo=groupBidBondInfo(bidBondInfoList,project.getWinningName(),ruser.getAccount());//组装履约保证金信息对象
			if(bidBondInfo==null){//未缴纳履约保证金
				return false;
			}
		}else{
            return false;
        }
		return true;
	}

	/**
	 * 组装履约保证金信息对象
	 * @param winningName 中标人单位名称
	 * @return
	 */
	private DepositReturn groupBidBondInfo(List<Bank> list, String winningName,String account) {
		for (Bank bank : list) {
			if(bank.getInName()!=null&&bank.getInName().equals(winningName)&&bank.getInAcct().equals(account)){
				DepositReturn dr=new DepositReturn();
				ComposeIdPK composeIdPK = new ComposeIdPK();
    			composeIdPK.setCompanyName(bank.getInName());
    			composeIdPK.setDepositType(Constant.DEPOSIT_TYPE_BIDDER);
				dr.setPk(composeIdPK);
				String date = bank.getInDate() + bank.getInTime(); // 拼接日期
				try {
					dr.setTransTime(new SimpleDateFormat("yyyyMMddhhmmss").parse(date));// 时间
				} catch (ParseException e) {
					e.printStackTrace();
				}
				dr.setTnAmount(new BigDecimal(bank.getInAmount()));// 金额再次更新
				return dr;
			}
		}
		return null;
	}

	/**
	 * description 判断履约保证金是否缴纳
	 * author shy
	 * date 2017-2-8
	 */

	private boolean isPayDepositReturn(ProjectInfo projectInfo) {
		boolean result = false;
		if(projectInfo.getExecuteBankAuthCode()==null){
			result= false;
		}else{
		List<Bank> bidBondInfoList = depositExecuteService.getDepositList(projectInfo.getId());
		if (bidBondInfoList!=null&&bidBondInfoList.size() > 1) {//系统默认生成一条空记录所有size>1
			for (Bank bank : bidBondInfoList) {
				if (bank.getInName()!=null && bank.getInName().equals(projectInfo.getWinningName())) {
					result = true;
				}
			}
		   }
		}
		return true;
	}


	/**
	 * @description 进入变更页面
	 * @date 2017-3-17
	 * @param projectId
	 * @author shy
	 * @return
	 */
	@RequestMapping("/bizmanager/getChangePage")
	public ModelAndView getChangePage(String projectId){
		ModelAndView mv = new ModelAndView();
		mv.addObject("projectId", projectId);
		ProjectInfo projectInfo  = this.projectInfoService.get(ProjectInfo.class,projectId);
		if(projectInfo.getAuditable()!=true){
			mv.addObject("isBid",false);
			mv.setViewName("/proj/bizmanager/bidder-change-noEvaluation");
		}else{
			ProjectBidInfo bidderInfo = this.projectBidService.getBidderInfo(projectId, projectInfo.getWinningId());
			mv.addObject("bidInfoId", bidderInfo.getId());
			mv.addObject("isBid",true);
			mv.setViewName("/proj/bizmanager/bidder-change");
		}

		return mv;
	}


	/**
	 * @description 获取有效的投标信息
	 * @date 2017-3-17
	 * @author shy
	 * @return
	 */
	@RequestMapping("/bizmanager/findValidBidInfo")
	@ResponseBody
	public JSONObject findValidBidInfo(ProjectInfo pro,Page page){
		RegisterUser bidder = new RegisterUser();
		this.projectBidService.findValidBidInfo(pro,page);
		List<ProjectBidInfo> list = page.getResult();
		for(ProjectBidInfo projectBidInfo : list){
			bidder=this.registerUserService.get(RegisterUser.class, projectBidInfo.getUserId());
			if(bidder!=null){
				projectBidInfo.setSocietyCode(bidder.getSocietyCode());
			}
		}
		return CommUtil.getPageJSONData(page, true);
	}


	/**
	 * @description 变更投标人
	 * @date 2017-3-17
	 * @author shy
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/bizmanager/changeBidder")

	public void changeBidder(BidderChange bidderChange,HttpSession session,HttpServletResponse resp,String budgetMenuData) throws IOException{
		String result ="";
		User user = (User) session.getAttribute("loginUser");
		ProjectInfo projectInfo = this.projectBidService.get(ProjectInfo.class, bidderChange.getProjectId());
	    ProjectBidInfo projectBidInfo = this.projectBidService.getBidderInfo(projectInfo.getId(), bidderChange.getNewBidderId());
		if(bidderChange==null ||projectInfo==null){
			result= Constant.SAVE_UN_SUCCESS;
		}else{
		projectInfo.setHitMoney(projectBidInfo.getBidAmount());
		projectInfo.setWinningId(bidderChange.getNewBidderId());
		projectInfo.setWinningName(bidderChange.getNewBidderName());
		bidderChange.setOldBidderId(projectInfo.getWinningId());
		bidderChange.setOldBIdderName(projectInfo.getWinningName());
		bidderChange.setOperatorId(user.getId());
		bidderChange.setOperateName(user.getName());
		bidderChange.setUpdateTime(new Date());
	// 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(projectInfo.getId());
					//res.setFunctionFlog(25);
					bidderChange.setResourceId(res.getId());
					bidderChange.setResourceName(res.getOldName());
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}

		try {
			this.projectInfoService.saveOrUpdate(projectInfo);
			this.projectBidService.saveOrUpdate(bidderChange);
			result= Constant.SAVE_SUCCESS;
		} catch (Exception e) {
		   e.printStackTrace();
		   result= Constant.SAVE_UN_SUCCESS;
		}
	}
		resp.getWriter().print(result);
 }


	/**
	 * @param ids
	 * @param projectId
	 * @param session
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/bizmanager/changeBidderNoEvaluation")
	public void changeBidderNoBid(String ids,String projectId,String bidReason,String budgetMenuData,HttpSession session,HttpServletResponse resp) throws IOException {
		User user = (User) session.getAttribute("loginUser");
		ProjectInfo projectInfo = this.projectBidService.get(ProjectInfo.class, projectId);
         String result="";
		 String oldBidName="";
		 String newBidName="";
         //变更信息
         BidderChange bg = new BidderChange();
         bg.setChangeReason(bidReason);
         bg.setProjectId(projectId);
         bg.setOperatorId(user.getId());
         bg.setNewBidderId(ids);
		//获取旧的中标信息
		List<ProjectBidInfo> bidInfos = this.projectInfoService.getProjectBiddersByProjId(projectInfo.getId());
		String[] bidIds = ids.split(",");
		ArrayList oldBidIds=new ArrayList();
		//构建数组（旧的中标信息）
		for(ProjectBidInfo bf:bidInfos){
			oldBidIds.add(bf.getUserId());
		}
		//原中标人改为非中标人
		for(ProjectBidInfo bf:bidInfos){
			//判断新中标人id 中是否包含原中标人id
			oldBidName+=bf.getBidderName()+",";
		//	boolean isContains = Arrays.asList(bidIds).contains(bf.getUserId());
			//if(isContains!=true){
                bf.setIsMultHit(false);
                try {
					this.projectBidService.saveOrUpdate(bf);
				}catch (Exception e){
                	e.printStackTrace();
                	result="removeIsMultHitError";
					resp.getWriter().print(result);
				}
		//	}
		}

		bg.setOldBIdderName(oldBidName.substring(0, oldBidName.length() -1));
		//增加新中标人
		for(int i=0;i<bidIds.length;i++){
			//判断新中标人id 是不是在原中标人id中存在
			ProjectBidInfo pbInfo=projectInfoService.getProjectBidderByProjIdAndBidderId(projectId,bidIds[i].toString());
			newBidName+=pbInfo.getBidderName()+",";
			//boolean isContains2 = Arrays.asList(oldBidIds).contains(bidIds[i]);
		//	if(isContains2 != true){
				//增加中标标记
                pbInfo.setIsMultHit(true);
                try {
					this.projectBidService.saveOrUpdate(pbInfo);
				}catch (Exception e){
					e.printStackTrace();
					result="setIsMultHitError";
					resp.getWriter().print(result);
			}
		// }
	   }
	   bg.setNewBidderName(newBidName.substring(0, newBidName.length() -1));
	   bg.setUpdateTime(new Date());
		// 项目关联清单附件信息
		if (budgetMenuData != null) {
			String budgetMenuStr[] = budgetMenuData.split(",");
			Resources res = null;
			for (String budgetMenuId : budgetMenuStr) {
				res = FileResUtil.getResources(budgetMenuId);
				if (res != null) {
					res.setBusinessId(projectInfo.getId());
					//res.setFunctionFlog(25);
					bg.setResourceId(res.getId());
					bg.setResourceName(res.getOldName());
					this.projectInfoService.saveOrUpdate(res);// 更新
				}
			}
		}
		try {
			this.projectBidService.saveOrUpdate(bg);
			result="success";
			resp.getWriter().print(result);
		}catch (Exception e){
			e.printStackTrace();
			result="saveBgError";
			resp.getWriter().print(result);
		}



	 }


	/**
	 * 小微企业折扣保存
	 * @return
	 */
	@RequestMapping("/expert/doSaveDiscount")
	@ResponseBody
	public Boolean doSaveDiscount(String bidId,Double discountAmount) {
		//获取投标信息
		ProjectBidInfo pb = this.projectBidService.get(ProjectBidInfo.class, bidId);
		pb.setDiscountAmount(discountAmount);
		this.projectBidService.save(pb);
		return true;
	}

	/**
	 * @description 进入履约保证金明细页面
	 * @author shy
	 * @date 2016-12-23
	 */
	@RequestMapping("/finance/excuteDepositList")
	@ResponseBody
	public ModelAndView excuteDepositList(HttpSession session, String projectId) {
		ProjectInfo projectInfo = projectInfoService.get(ProjectInfo.class, projectId);
		ModelAndView mv = new ModelAndView("/proj/leader/excute-deposit-show");
		mv.addObject("projectId", projectId);
		mv.addObject("bidderId", projectInfo.getWinningId());
		return mv;
    }



	/**
	 * 计算工作日
	 * @param date 起始日期
	 * @param addDay 计算的天数
	 * @return 计算结果日期
	 * @throws Exception
	 */
	@RequestMapping("/computeWorkDayDate")
	@ResponseBody
	public String isWorkDayToShot(Date date,Integer addDay) throws Exception {
		String resultDate = DateUtils.computeWorkDayDateStr(holidaySetServiceImpl, date, addDay);
		return resultDate;
	}


//	@RequestMapping("/bidderChangeListPage")
//	public ModelAndView bidderChangeListPage(){
//		ModelAndView mv = new ModelAndView();
//		mv.setViewName("/pro/bizmanager/project-change-list");
//		return mv;
//	}
//
//	@RequestMapping("/bidderChangeList")
//	@ResponseBody
//	public JSONObject bidderChangeList(Page page,HttpSession session){
//		List<BidderChange> list =this.projectBidService.getBidChangList(page);
//		return CommUtil.getPageJSONData(page, true);
//	}

	/**
	 * 获取没有缴纳履约保证金的中标单位
	 * @param bidBondInfoList
	 * @param bidInfos
	 * @return
	 */
	private String getNoBidBondName(List<Bank> bidBondInfoList,List<ProjectBidInfo> bidInfos ){
		//查询缴纳过的中标单位
		List<String> payBidderId=new ArrayList<>();//已经缴纳过的中标单位中标信息id
		for (ProjectBidInfo bidInfo : bidInfos) {
			RegisterUser register = this.projectInfoService.get(RegisterUser.class, bidInfo.getUserId());
			for (Bank bank : bidBondInfoList) {
				if(bidInfo.getBidderName().equals(bank.getInName())
						&&bank.getInAcct().equals(register.getAccount())){
					payBidderId.add(bidInfo.getId());
				}
			}
		}

		//获取没有缴纳保证的单位名称
		StringBuffer noBondName=new StringBuffer("");//没有缴纳保证的单位名称
		for (ProjectBidInfo bidInfo : bidInfos) {
			if(!payBidderId.contains(bidInfo.getId())){//没有缴纳保证金
				noBondName.append("『"+bidInfo.getBidderName()+"』");
			}
		}
		return noBondName.toString();
	}


	/**
	 * 校验变更公告公示时间是否满足工作日
	 * @param startDate
	 * @param endTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/isOkWorkDay")
	@ResponseBody
	public boolean isOkWorkDay(Date startDate, Date endTime) throws Exception {
		DataSet dataset = holidaySetServiceImpl.get(DataSet.class, Constant.DATASET_ID);
		boolean flag = true;
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
		Calendar calStart = Calendar.getInstance();
		calStart.setTime(endTime);
		List<String> dates = this.holidaySetServiceImpl.findAllByYear(calStart.get(Calendar.YEAR)+"");
		if (dates.contains(sdf1.format(calStart.getTime()))) {
			flag = false;
		} else {
			//采购确认时间
			Calendar cd = Calendar.getInstance();
			cd.setTime(startDate);
			String validTimeStr=sdf1.format(cd.getTime())+" 00:00:00";

			//开标时间
			Calendar cdBid = Calendar.getInstance();
			cdBid.setTime(sdf1.parse(validTimeStr));

			//相隔天数
			long betweenDay = (calStart.getTime().getTime()-cdBid.getTime().getTime())/(1000*3600*24);
			int index=0;
			while(betweenDay+1>0){
				if (!dates.contains(sdf1.format(calStart.getTime()))) {
					index++;
				}
				calStart.add(Calendar.DAY_OF_YEAR, -1);
				betweenDay--;
			}
			if(index<= dataset.getChangePublicity()){//dataset 设置
				flag=false;
			}
		}
		return flag;
	}
}
